Conclusion: In the upward transformation, the reference of the parent class points to the object of the subclass, and this reference object cannot call the method of the subclass when calling the method, because the compiled type is the element on the left of the "= sign", and the compiled type is in the compilation stage. OK, since the cry() method does not exist in the parent class, it cannot be inherited in the subclass, so it can only be defined by itself. The eat() method can be called because the right side of the "= sign" is the running type, and the running type is to find the method from the subclass upward (parent class), so the dog reference can call the eat() and sleep() methods. Go directly to the code.
public class Animal {
public void eat(){
System.out.println("吃xx");
}
public void sleep(){
System.out.println("睡觉");
}
}
public class Dog extends Animal{
@Override
public void eat() {
System.out.println("吃肉");
}
public void cry(){//这个时子类特有的方法
System.out.println("狗叫");
}
}
public class Test {
public static void main(String[] args) {
Animal dog = new Dog();
dog.eat();
dog.sleep();
//dog.cry(); 这个会报错
}
}
The result of the operation is as follows
eat meat
sleep