父类:
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 void say()
{
System.out.println(name+"\t"+age);
}
}
子类:
public class Student extends Person {
private double score;
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
public Student(String name, int age, double score) {
super(name, age);
this.score = score;
}
@Override //重写注解
public void say()
{
System.out.println(getName()+"\t"+getAge()+"\t"+score);
}
public void study()
{
System.out.println("学生"+getName()+"正在学习java");
}
}
子类:
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 void say()
{
System.out.println(getName()+"\t"+getAge()+"\t"+salary);
}
public void teach()
{
System.out.println("老师"+getName()+"正在讲课");
}
}
测试类:
public class Test {
public static void main(String[] args) {
//多态数组
Person[] person = new Person[5]; //创建对象并实例化
person[0] = new Person("李白",18);
person[1] = new Student("韩信",99,88.8); //向上转型
person[2] = new Student("露娜",18,99.9);//向上转型
person[3] = new Teacher("老子",66,2000);//向上转型
person[4] = new Teacher("墨子",88,5000);//向上转型
//循环遍历多态数组
for(int i=0;i<person.length;i++)
{
person[i].say(); //动态绑定机制
//运用java关键词 instanceof 关键词
if(person[i] instanceof Student)
{
//就向下转型(上面已经向上转型)
Student student = (Student)person[i]; //向下转型
student.study();
}
else if(person[i] instanceof Teacher)
{
//重复上面的过程
Teacher teacher = (Teacher)person[i];
teacher.teach();
}
else
System.out.println("输入错误!");
}
}
}