在多态中,子类对象向上提升为父类类型后,对于数据域和静态的,编译和运行都是父类的,但是方法却是编译看父类有没有,没有就不通过编译,运行则是执行子类的方法。为什么呢?
public class Test {
public static void main(String[] args) {
Parent p = new Child();
System.out.println(p.name + "\t" + p.address);
p.sayName();
}
}
class Parent {
public String name = "father";
public static String address = "JiangXi";
public void sayName() {
System.out.println(name + "\t" + address);
}
}
class Child extends Parent {
public String name = "son";
public static String address = "ZheJiang";
public void sayName() {
System.out.println(name + "\t" + address);
}
}
执行结果为
father JiangXi
son ZheJiang