问题
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 superclass type, but I get the child's overridden method every time. This also happens when I use polymorphism.
Questions are in the comments inside code below... Thanks in advance.
class Parrent{
public void test(){
System.out.println("parentTest");
}
}
class Child extends Parrent{
@Override
public void test(){
System.out.println("childTest");
}
}
class StartProgram{
public static void main(String[] args) {
Parrent p1 = new Parrent();
p1.test(); // output: parentTest
Child c1 = new Child();
c1.test(); // output: childTest
Parrent p2 = new Child();
p2.test(); // why returns child method? becouse it's overriden?
((Parrent) new Child()).test(); // why returns child method if I cast it?
}
}
回答1:
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.
回答2:
The actual type is Child, therefore when you call a method, the Child's method will be called. It doesn't matter whether the reference type is of Parent, it's the actual type of the object that matters.
You can't "cast to superclass" in order to call the Parent's method either.
回答3:
Method resolution occurs at runtime, not compile time. The object's class (its behaviour) declares an implementation of the method, so that is used.
Being able to refer to objects by their superclass is the essence of OOP.
See Liskov substitution principle
回答4:
Here the child method gets called because functions are bind at runtime and in your reference memory is of child
((Parrent) new Child()).test();// new Child() means memory is of child
来源:https://stackoverflow.com/questions/21613540/casting-to-superclass-and-calling-overriden-method