java(二十五)【面向对象】多态-转型

多态自始自终都是子类对象在做变化

注意:

  不要将父类对象转成子类类型

  我们能转换的是父类应用指向了自己的子类对象时,该应用可以被提升,也可以被强制转化

 1 abstract class Animal{
 2     abstract void eat();
 3 }
 4 class  Cat extends Animal{
 5     public void eat(){
 6         System.out.println("吃鱼");
 7     }
 8     public void catchMouse(){
 9         System.out.println("抓老鼠");
10     }
11 }
12 class Dog extends Animal{
13     public void eat(){
14         System.out.println("吃骨头");
15 }
16     public void Kanjia()
17     {
18         System.out.println("看家");
19     }
20 }
21 public class Single {
22     public static void main(String[] args){
23         /*
24         Animal a=new Cat(); //向上转型
25         a.eat();
26         //如果想要调用猫的特有方法时,如何操作?
27         //强制将父类引用转成子类类型
28         Cat c=(Cat)a; //向下转型
29         c.catchMouse();
30         //千万不要出现如下操作
31         //Animal a =new Animal();
32         //Cat c=(Cat)a;
33         Animal s=new Dog();
34         Dog d=(Dog)s;
35         d.Kanjia();
36         };
37         */
38         function(new Dog());
39         function(new Cat());
40         }    
41     public static void function(Animal a) //Animal a =new Dog();
42     {
43         a.eat();
44         if (a instanceof Cat) {
45             Cat c=(Cat)a;
46             c.catchMouse();
47         }
48         else if (a instanceof Dog) {
49             Dog d=(Dog)a;
50             d.Kanjia();
51         }
52     }
53     }

 

运行结果:

  

 

posted @ 2015-09-15 08:28  花花妹子。  阅读(134)  评论(0)    收藏  举报