java多态2

 1 package pet_2;
 2 
 3 public  class Pet {
 4      private String name;
 5 
 6   public String getName() {
 7     return name;
 8   }
 9 
10   public void setName(String name) {
11     this.name = name;
12   }
13 }
14 
15 
16 package pet_2;
17 
18 public class Dog extends Pet {
19    
20      public void play() {
21        System.out.println("狗玩盘子");
22      }
23 }
24 
25 
26 package pet_2;
27 
28 public class Cat extends Pet {
29   
30    public void play() {
31        System.out.println("猫抓老鼠");
32      }
33 }
34 
35 
36 package pet_2;
37 
38 public class Master {
39        public static Pet getPet(int typeid) {//静态方法可以直接类名调用,无需实例化一个对象
40          Pet pet=null;
41          if(typeid==1) {
42            pet=new Cat();//or Cat cat=new Cat();
43          }else if(typeid==2) {
44            Dog dog=new Dog();
45            pet=dog;
46          }
47          
48          return pet;
49        }
50        
51        public void play(Pet pet) {
52          //if(如果pet是dog) instanceof
53          if(pet instanceof Dog) {
54            Dog dog=(Dog)pet;
55            dog.play();
56          }
57          if(pet instanceof Cat) {
58            Cat cat=(Cat)pet;
59            cat.play();
60          }
61        }
62 } 
63 
64 
65 package pet_2;
66 
67 public class Mastertest {
68 
69   public static void main(String[] args) {
70     Master master=new Master();
71     //Pet dog =new Dog();
72     Pet dog=Master.getPet(2);
73     master.play(dog);
74   }
75       
76 }

 

上一篇:gradle-在一个模块中引入其它模块


下一篇:tidyverse|数据分析常规操作-分组汇总(sumamrise+group_by)