多态中成员访问特点

 1 package duoTai02;
 2 
 3 public class Animal {
 4 
 5     public int age = 40;
 6 
 7     public void eat(){
 8         System.out.println("动物吃东西");
 9     }
10 }
 1 package duoTai02;
 2 
 3 public class Cat extends Animal{
 4 
 5     public int age = 20;
 6     public int weight = 10;
 7 
 8     @Override
 9     public void eat() {
10         System.out.println("猫吃鱼");
11     }
12 
13     public void playGame(){
14         System.out.println("猫捉迷藏");
15     }
16 }
 1 package duoTai02;
 2 /*
 3     多态中成员访问特点
 4         成员变量:编译看左边,执行看左边
 5         成员方法:编译看左边,执行看右边
 6 
 7         原因:因为成员方法有重写,而成员变量没有
 8  */
 9 public class AnimalDemo {
10     public static void main(String[] args) {
11         //有父类引用指向子类对象
12         Animal a =new Cat();
13 
14         System.out.println(a.age);
15        // System.out.println(a.weight);
16 
17         a.eat();
18        //a.playGame();
19     }
20 }

 

posted @ 2021-01-18 22:16  找不到北的北  阅读(107)  评论(0)    收藏  举报