多态的应用-多态数组
多态的应用-多态数组
- 多态数组
- 数组的定义类型为父类型,里面保存的实际元素类型是子类类型
- 多态参数
- 方法定义的形参类型为父类型,实参类型允许为子类型
多态数组
应用实例:现有一继承结构如下:要求创建1个Person对象。2个 Student 对象和2个Teacher 对象,统一放在数组中,并调用 say方法。应用实例升级:如果调用子类特有的方法,比如 Teacher 有一个 teach,Student 有一个 study 调用。
Person.java
public class Person{
private String name;
private int age;
public Person(String name, int age){
this.name = name;
this.age = age;
}
public void setname(String name){
this.name = name;
}
public String getname(){
return name;
}
public void setage(int age){
this.age = age;
}
public int getage(){
return age;
}
public String say(){
return name + "\t" + age;
}
}
Student.java
public class Student extends Person{
private double score;
public Student(String name, int age, double score){
super(name, age);
this.score = score;
}
public void setscore(int score){
this.score = score;
}
public double getscore(){
return score;
}
// Override Person say
public String say(){
return super.say()+" score "+ score;
}
}
Teacher.java
public class Teacher extends Person{
private double salary;
public Teacher(String name, int age, double salary){
super(name, age);
this.salary = salary;
}
public void setsalary(){
this.salary = salary;
}
public double getsalary(){
return salary;
}
// Override Person say
public String say(){
return super.say() + " salary" + salary;
}
}
mains.java
public class mains{
public static void main(String[] args) {
Person[] persons = new Person[5];
persons[0] = new Person("jack", 20);
persons[1] = new Student("jack", 20, 100);
persons[2] = new Student("smith", 20, 60);
persons[3] = new Teacher("scott", 40, 40000);
persons[4] = new Teacher("king", 50, 50000);
for (int i = 0; i < persons.length; i++) {
// Person[i] 的编译类型是 Person ,运行类型根据实际的情况由 jvm 来判断
System.out.println(persons[i].say());
}
}
}
jack 20
jack 20 score 100.0
smith 20 score 60.0
scott 40 salary40000.0
king 50 salary50000.0