介绍
接的上面的,现在我们在两个子类student 和teacher中分别添加study 和teacher方法,但父类中没有该方法。那么就需要用到我们的向下转型了
代码
student
package hansunping;
public class student extends person {
private String name;
public int age;
private double score;
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
public student( String name,int age, double score) {
// TODO Auto-generated constructor stub
super(name, age);
this.score=score;
}
@Override//重写父类say方法
public String say() {//返回名字年龄
return super.say()+"scor="+score;
}
public void study() {
System.out.println("学生"+getName()+"正在学习");//注意,这里子类没有getname方法,并且name在子类中private,要通过公有方法调用。
}
}
teacher
package hansunping;
public class teacher extends person {
private double salary;
public teacher(String name,int age,double salary ) {
// TODO Auto-generated constructor stub
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()+"scor="+salary;
}
public void tea() {
System.out.println("老师"+getName()+"正在教书");//注意,这里父类没有getname方法,并且name在子类中private,要通过公有方法调用。
}
}
person父类
package hansunping;
public class person{
private String name;
public int age;
public person(String name,int age) {
// TODO Auto-generated constructor stub
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+"\t"+age;
}
}
demon主类
package hansunping;
public class demon1 {
public static void main(String[] args) {
person[] persons=new person[5];//你尝试创建一个名为 persons 的 Person 类型数组,该数组有5个元素:
persons[0]=new person("jack", 20);
persons[1]=new student("jack", 20,100);
persons[2]=new student("smith", 18,30.1);
persons[3]=new teacher("scott", 30,2000);
persons[4]=new teacher("king", 30,2000);
//循环遍历数组。调用say
for (int i = 0; i < persons.length; i++) {
System.out.println(persons[i].say());//动态绑定
//persons[i].study(),如果这样的话,
//persons[i].teach(),如果这样的话,由于编译类型是父类,父类没有study等方法。那么我们这里需要强制转换
if (persons[i] instanceof student) {//instanceof是判断运行时的
student stu=(student)persons[i];//向下转型,把person的转为student,也可以用(student)person[i].study
stu.study();
}
else if (persons[i] instanceof teacher) {
teacher te=(teacher)persons[i];
te.tea();
}
else {
System.out.println("对不起了,编译系统不支持");
}
}
//、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、
//如果我们将student类的say()方法注销,他寻找student类的say方法无果后,会再向它的父类调用say方法。返回我是人类,效果等同于
}
}
运行结果
jack 20
对不起了,编译系统不支持
jack 20scor=100.0
学生jack正在学习
smith 18scor=30.1
学生smith正在学习
scott 30scor=2000.0
老师scott正在教书
king 30scor=2000.0
老师king正在教书
那么为什么又 对不起编译系统不支持呢
persons[0]=new person("jack", 20);
这里还是有个运行对象为person类的
这就是我们的向下转型了