这是我的代码
class Animal{
public int numOf=3;
}
class Dog extends Animal{
public int numOf=4;
}
class TestCase{
public static void main(String[] args){
Animal a = new Dog();
Dog d = new Dog();
System.out.println(a.numOf);
System.out.println(d.numOf);
}
}
当我a.numOf
时,它不应该是4,就像方法一样吗?
答案 0 :(得分:7)
多态性不适用于字段。
根据访问的变量的声明类型解析字段。
System.out.println(a.numOf); // refers to A's, since a's declared type is A
System.out.println(d.numOf); // refers to D's, since d's declared type is D
此处有hiding
个案例。