问题
Why reference variable of child class can't point to object of parent? i.e
Child obj = new Parent();
However we can do vice versa Kindly answer with memory view (heap)
回答1:
There is no reason which has something to do with the memory. It's much more simple. A subclass can extend the behaviour of its superclass by adding new methods. While it is not given, that a superclass has all the methods of its subclasses. Take the following example:
public class Parent {
public void parentMethod() {}
}
public class Child extends Parent {
public void childMethod() {}
}
Now let's think about what would happen if you could assign an instance of Parent
to a variable of type Child
.
Child c = new Parent(); //compiler error
Since c
is of type Child
, it is allowed to invoke the method childMethod()
. But since it's really a Parent
instance, which does not have this method, this would cause either compiler or runtime problems (depending on when the check is done).
The other way round is no problem, since you can't remove methods by extending a class.
Parent p = new Child(); //allowed
Child
is a subclass of Parent
and thus inherits the parentMethod()
. So you can invoke this method savely.
来源:https://stackoverflow.com/questions/43296084/why-cant-i-assign-a-parent-class-to-a-variable-of-subclass-type