现有继承结构如下: Person对象类,Student类, Teacher类继承Person类。
如何调用Student类特有类study和Teacher类特有类teach呢。
目录
1. Student特有学习方法
public void study(){
System.out.println("学生" +getName()+"正在学习");
}
2. Teacher特有教书方法
public void teach(){
System.out.println("teacher " +getName() + "正在讲课");
}
3. Main测试方法
public static void main(String[] args) {
//两个student, 两个teacher,都放在数组中,并且调用say方法。
Person[] persons = new Person[5];
persons[0] = new Person("jack", 20);
persons[1] = new Student("jackie", 18, 100);
persons[2] = new Student("smith", 19, 30.1);
persons[3] = new Teacher("scott", 30, 20000);
persons[4] = new Teacher("king", 50, 25000);
for (Person person : persons) {
System.out.println(person.say());
if(person instanceof Student){
((Student) person).study();
} else if(person instanceof Teacher){
((Teacher) person).teach();
}
}
}
使用InstanceOf判断是否是某类型和某类型的子类对象。如果是则向下转型成该方法调用。