Java 多态 案列

 1 package com.bytezreo.duotai;
 2 
 3 //多态性的使用 举例一
 4 public class AnimalTest
 5 {
 6     public static void main(String[] args) 
 7     {
 8         AnimalTest test = new AnimalTest();
 9         test.func(new Dog());
10         
11         
12         test.func(new Cat());
13         
14         
15     }
16     
17     //声明是 animal          Animal animal = new Dog();
18     public void func(Animal animal)
19     {
20         animal.eat();
21         animal.shout();
22     }
23     
24     
25     //没有多态性的时候
26 //    public void func(Dog dog)
27 //    {
28 //        dog.eat();
29 //        dog.shout();
30 //    }
31 //    
32 //    public void func(Cat cat)
33 //    {
34 //        cat.eat();
35 //        cat.shout();
36 //    }
37 //    
38 //    
39     
40 }
41 
42 class Animal
43 {
44     public void eat()
45     {
46         System.out.println("动物:进食");
47     }
48     public void shout()
49     {
50         System.out.println("动物:叫");
51     }
52     
53     
54     
55     
56     
57 }
58 
59 class Dog extends Animal
60 {
61     public void eat()
62     {
63         System.out.println("狗:吃骨头");
64     }
65     public void shout()
66     {
67         System.out.println("狗:汪汪汪");
68     }
69 }
70 
71 
72 
73 class Cat extends Animal
74 {
75     public void eat()
76     {
77         System.out.println("猫:吃大鱼");
78     }
79     public void shout()
80     {
81         System.out.println("猫:喵喵喵");
82     }
83 }
84 
85 //举例二
86 
87 class Order
88 {
89     public void method(Object obj)
90     {
91         
92     }
93 }

 

posted on 2021-09-20 18:07  Bytezero!  阅读(37)  评论(0编辑  收藏  举报