问题
I am Learning Java, while trying to understand inheritance. I couldn't figure out why the overridden method at the subclass walk() executed but not the other xyz() method.
class Person{
public void walk() { System.out.println("walking like a person "); }
}
public class Soldier extends Person{
@override
public void walk() { System.out.println("marching like a soldier "); }
public void xyz() { System.out.println("xyzng like a pro"); }
public static void main(String[] args) {
Person sp = new Soldier();
sp.walk();
sp.xyz();
}
}
Here is my question, if the following method call works fine and calls the Soldier method walk,
sp.walk();
why the compiler complain about the this call?
sp.xyz();
回答1:
At the compile time parent class reference 'sp' can only see method inside it. if you want to access as ((Soldier) sp).xyz()
回答2:
You may want to take a look at this answer.
Basically, xyz
method is defined in a subclass of Person
and in general case compiler can't know (and should not know) whether the referenced instance is Soldier
or some other subclass which does not define xyz
method.
回答3:
In Java, "objects" are not values themselves -- they must always be manipulated through references; when you create an object, you get a reference; when you access a field or call a method, you do it through the reference. When you assign one reference to another, it copies the reference, so you have multiple pointers to the same object.
Your question asks why Soldier.xyz() is not accessible when the
Soldier
object is stored in aPerson
reference. The answer is the intersection of "polymorphism" and "static typing". Because Java is statically typed at compile time you get certain guarantees from the compiler but you are forced to follow rules in exchange or the code won't compile. Here, the relevant guarantee is that every instance of a subclass (e.g.Soldier
) can be used as an instance of its super class (e.g.Person
).
Please take a look at this it is explained in more details thread As of the tutorial guide to truly understand the inheritance please take a look at this article
回答4:
That's clear. because your reference to object(sp) is of type Person, that means sp contains all property and methods of Person only. Even you get instance of Soldier, but your reference is from Person type yet.
回答5:
Person
is a class.sp
is an object, it is an instance ofPerson
- Class
Person
haven't method namedxyz()
, thereforcesp.xyz()
not working.
(You have a typo, we use @Override
, not @override
)
回答6:
In the compile-time, IDE only knows about the static Object type is Person class. You can see compile-time reference rule here: https://www.cs.cornell.edu/courses/JavaAndDS/files/compiletimeReferenceRule.pdf
来源:https://stackoverflow.com/questions/32283961/why-cant-i-call-a-subclass-method-using-a-reference-of-a-parent-type-that-refer