05_多态转型内存图解

 1 package duoTai04;
 2 
 3 public class Cat extends Animal {
 4 
 5     @Override
 6     public void eat(){
 7         System.out.println("猫吃鱼");
 8     }
 9 
10     public void playGame(){
11         System.out.println("毛捉迷藏");
12     }
13 }
1 package duoTai04;
2 
3 public class Animal {
4     public void eat(){
5         System.out.println("动物吃东西");
6     }
7 }
 1 package duoTai04;
 2 /*
 3     多态中的转型
 4         向上转型
 5             从子到父
 6             父类引用指向子类对象
 7         向下转型
 8             从父到子
 9             父类引用转为子类对象
10  */
11 
12 public class AnimalDemo {
13     public static void main(String[] args) {
14         //多态
15         Animal a = new Cat();   //向上转型
16         a.eat();
17 
18 
19         Cat c = new Cat();
20         c.eat();
21         c.playGame();
22 
23         Cat cat = (Cat)a;  //向下转型
24         cat.eat();
25         cat.playGame();
26 
27     }
28 }

 

posted @ 2021-02-22 19:49  找不到北的北  阅读(83)  评论(0)    收藏  举报