多态的案列题型

 1 package com.polyExercise;
 2 
 3 /*
 4         案例:数组的定义类型为父类类型,里面保存的实际元素类型为子类类型
 5         应用实例01;现有一个继承结构如下:要创建1个Person对象、2个student、2个Teacher对象
 6         统一放在数组中,并调用每个对象的say()方法
 7         Person类有名字、年龄等属性;
 8         student类有分数;
 9         Teacher类有薪水;
10 
11         应用实例02:如何调用子类特有的方法,比如Tacher有一个teach的方法,
12         student有一个study的方法,该如何调用?
13 
14     应用实例01分析:
15     1.先创建一个Person父类对象,并赋予属性和构造器及say方法
16     2.分别创建学生和老师两个子类对象,并赋予相应的属性和构造器和say方法
17     (方法可以通过重写调用父类的)
18     3.创建一个新的类,并建立一个新的数组对象,用来装Person类和学生、老师
19 
20     应用实例02分析
21     1.判断类型+向下转型
22     2.用instance of 判断person[i]是否属于学生类还是老师类,然后在进行向下转型
23  */
24 public class polyArry {
25     public static void main(String[] args) {
26         Person[] person = new Person[5];
27         person[0] = new Person("jack", 20);
28         person[1] = new student("mark", 18, 95.1);
29         person[2] = new student("smith", 19, 124);
30         person[3] = new Teacher("curry", 32, 23000);
31         person[4] = new Teacher("rose", 29, 20000);
32 
33         //for循环遍历,调用say方法
34         for (int i = 0; i < person.length; i++) {
35             //  person[i]是动态绑定机制,say()方法随i的变化而变化
36             // person[i]的编译类型是Person,运行类型是根据实际情况由jvm来判定
37             System.out.println(person[i].say());
38 
39             //判断是否属于学生或老师,然后进行向下转型,才能去调用子类特有的方法;
40             if (person[i] instanceof student) {
41                 student stu = (student) person[i];//向下转型
42                 stu.study();
43             }else if (person[i] instanceof Teacher){
44                 Teacher teacher = (Teacher) person[i];//向下转型
45                 teacher.teach();
46             }else if (person[i] instanceof Person){
47                 System.out.println();
48             }else {
49                 System.out.println("你输入的类型有误,请重新输入...");
50             }
51 
52         }
53     }
54 }

 

posted @ 2022-03-08 10:46  捞月亮的渔夫  阅读(49)  评论(0)    收藏  举报