多态与数组的结合:多态数组
父类建立一个数组,存储父类和子类的属性信息。
这里是父类Person,两个属性,一个say方法,用于返回属性信息。
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String say(){
return name+ " "+age;
}
}
下面是两个子类,重写了say方法,并该有自己的特有方法
public class Student extends Person{
private double score;
public Student(String name, int age, double score) {
super(name, age);
this.score = score;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
@Override
public String say() {
return super.say()+ this.score;
}
public void study(){
System.out.println("学生学习"+getName());
}
}
public class Teacher extends Person{
private double salary;
public Teacher(String name, int age, double salary) {
super(name, age);
this.salary = salary;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
@Override
public String say() {
return super.say() +this.salary;
}
public void teach(){
System.out.println("老师教学"+getName());
}
}
public class ployArr {
public static void main(String[] args) {
Person persons[]=new Person[5];//建立一个索引为5的数组,Person类的数组。指向所有子类
persons[0]=new Person("赵刚",21);
persons[1]=new Student("小张",12,78);
persons[2]=new Teacher("小李",23,5000);
persons[3]=new Student("小黑",23,12);
persons[4]=new Person("小白",23);
//子类进行初始化并存储在数组中。
for (int i=0;i<persons.length;i++){//循环数组
System.out.println( persons[i].say());//调用子类重写的say方法并输出
if (persons[i] instanceof Student){//这里是为了调用子类特有的方法,instanceof判断是不是
Student类或Student的子类
// Student student=(Student)persons[i];//向下转型
((Student) persons[i]).study();
} else if (persons[i]instanceof Teacher) {//这里是判断是否是Teacher类或其子类
((Teacher) persons[i]).teach();//
}else if(persons[i]instanceof Person){//如果是Person类则不做处理
}else {
System.out.println("方法有误");
}