Java 面向对象进阶 10 多态中调用成员的特点(黑马)
代码:
public class test {public static void main(String[] args) {Animal a = new Dog();System.out.println(a.name);a.show();}
}
class Animal{String name = "动物";public void show(){System.out.println("Animal --- show方法");}
}
class Dog extends Animal{String name = "狗";public void show(){System.out.println("Dog --- show方法");}
}
class Cat extends Animal{String name = "猫";public void show(){System.out.println("Cat --- show方法");}
}
运行结果为:
说明:
如果编译时,左边没有该成员变量会直接标红:
如果调用成员方法时,编译时发现父类没有该方法,就会标红
说明:
理解:
内存图展示:
如果时Dog d = new Dog();那么就直接区子类找name,不会先去父类开始找,找不到再到父类去找;