58 多态实例

 1 class Demo15{
 2     public static void main(String[] args) {
 3         // Animal a1 = new Cat();
 4         // a1.eat();
 5 
 6         // Animal a2 = new Dog();
 7         // a2.eat();
 8         method(new Dog());
 9 
10     }
11 
12 public static void method(Animal a){
13     if (a instanceof Dog) {
14             Dog d= (Dog)a;
15         System.out.println(d.age);    
16         
17     }
18     
19 
20 }
21 
22 
23 class Animal{
24 
25     public void eat(){
26         System.out.println("father");
27     }
28 
29 }
30 
31 class Cat extends Animal{
32 
33     public void eat(){
34         System.out.println("吃猫食");
35     }
36 
37 
38 }
39 
40 class Dog extends Animal{
41     public int age = 10;
42     public void eat(){
43         System.out.println("吃狗食");
44     }
45 }
46 
47 
48 
49 // 条件一 :继承
50 // 条件二 :覆写  父类必须具有这个行为
51 // 要使用子类特有的 必须进行强转
52 // 一般都是用来做参数

 

posted @ 2017-01-28 16:07  panw3i  阅读(82)  评论(0编辑  收藏  举报