多态数组

image-20220720180345157

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package com.jhfuture.poly._polyarr__;

public class PloyArray {
public static void main(String[] args) {
Person person[]=new Person[3];
person[0]=new Person("这是个人");
person[1]=new Student("小明",15);
person[2]=new Teacher("李老师",1000);
for (int i = 0; i <person.length ; i++) {
//调用每一个say
//输出结果由每一个运行类型决定
person[i].say();
if (person[i] instanceof Student){
((Student)person[i]).Study();
}else if (person[i] instanceof Teacher){
((Teacher)person[i]).teacher();
}


}
}
}
//应用实例:现有一个

class Person{
String name;

public Person(String name) {
this.name = name;
}

public void say(){
System.out.println("here is Person"+getName());
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
Person(){

}
}
class Student extends Person{
String name;
int age;
public void say(){
System.out.println("here is Student"+getName());
}

public Student(String name, int age) {
this.name = name;
this.age = age;
}
public void Study(){
System.out.println("可以学习");
}

@Override
public String getName() {
return name;
}

@Override
public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}
}
class Teacher extends Person{
String name;
double salery;
public void say(){
System.out.println("here is Teacher"+getName());
}

public Teacher( String name1, double salery) {
this.name = name1;
this.salery = salery;
}
public void teacher(){
System.out.println("可以教书");
}

@Override
public String getName() {
return name;
}

@Override
public void setName(String name) {
this.name = name;
}

public double getSalery() {
return salery;
}

public void setSalery(double salery) {
this.salery = salery;
}
}

1
2
3
4
5
6
//输出
here is Person这是个人
here is Student小明
可以学习
here is Teacher李老师
可以教书