Casting to Superclass, and Calling Overriden Method

前端 未结 4 1797
梦如初夏
梦如初夏 2021-01-23 16:44

I have my next question. I have extended a class, Parrent and overridden one of its method in the Child class. I tried to cast the type to the supercla

4条回答
  •  清酒与你
    2021-01-23 17:21

    Casting is solely for the benefit of the compiler. The JVM doesn't know anything about it, and it does not affect what method gets called. The JVM tries to resolve a method by looking for something that matches the given signature, starting with the most specific class and working its way up the hierarchy towards the root (java.lang.Object) until it finds something.

    The purpose of polymorphism is so code calling some object doesn't have to know exactly what subclass is being used, the object being called takes care of its own specialized functionality. Having a subclass override a method means that objects of that subclass need to handle that method in their own particular way, and the caller doesn't have to care about it.

    Casting is for odd edge cases where your code can't know what type something is. You shouldn't need to cast if you know the super type (Parent in your example), the subclass should take care of itself.

提交回复
热议问题