定义的类型为父类类型,实际保存的是子类类型。如下图所示:
public class Test {
public static void main(String[] args) {
Persion[] persions = new Persion[5];//Persion类数组。和新建立数组一样。
persions[0] = new Persion("jack", 20);
persions[1] = new Student("timi", 18, "18");
persions[2] = new Student("王", 22, "89");
persions[3] = new Teacher("zhao0", 56, 8500);
persions[4] = new Teacher("xiao", 70, 8600);
for (int i = 0; i < persions.length; i++) {
//编译类型是Persion,运行类型是根据实际情况来执行。
//动态绑定机制。
//其实这都是父类的引用指向子类的对象。这才是实际情况下考虑的很多场景。
if (persions[i] instanceof Student) {//判断当前的Persions对象是否属于Student类。然后进行类型的转换。
((Student) persions[i]).study();//向下转型
//也可以写成上面的形式。Student student = (Student)persions[i];
} else if (persions[i] instanceof Teacher) {
((Teacher) persions[i]).teach();
}else{
System.out.println(persions[i].say());
}
}
}
}
public class Persion {
private String name;
private int age;
public Persion(String name, int age) {
this.name = name;
this.age = age;
}
//方法:
public String say() {
return "name = " + name + "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 class Student extends Persion {
private String score;
public Student(String name, int age, String score) {
super(name, age);
this.score = score;
}
@Override
public String say() {
return super.say() + " score = " + score;
}
public void study() {
System.out.println("学生" + getName() + "正在学习java" );
}
public String getScore() {
return score;
}
public void setScore(String score) {
this.score = score;
}
}
public class Teacher extends Persion{
private double salary;
public Teacher(String name, int age, double salary) {
super(name, age);
this.salary = salary;
}
@Override
public String say() {
return super.say() + "salary = " + salary;
}
public void teach() {
//这里为什么是要写getName呢,这是因为name 在本类是没有的,必须去调用父类的
//name,别忘记了set和get是啥的了,set是为了设置判断,get是为了在不同的类能够进行
//使用,因为他是private啊。只能在本类使用。所以用get获取。
System.out.println("老师" + getName() + "正在教英语");
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}