package overload;
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;
}
}
以上为父类
package overload;
public class Student extends Person {
private int id;
private double score;
public Student(String name, int age, int id, double score) {
super(name, age);
this.id = id;
this.score = score;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
public String say(){
// return "学生的" + super.say() + "id为" + id + "分数为" + score;
return "学生的" +getName() +"年龄" + getAge() + "id为" + id + "分数为" + score;
}
public void study(){
System.out.println("学生的study方法被调用");
}
}
以上为子类学生类
package overload;
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;
}
public String say() {
return "老师的" + super.say() + "薪水为" + salary;
}
public void teach(){
System.out.println("老师的teach方法被调用");
}
}
以上为子类教师类
package overload;
public class Test {
public static void main(String[] args) {
Person[] people = new Person[5];
people[0]=new Person("JAKE",18);
people[1]= new Student("ZJH",22,18076120,99.0);
//编译类型 Person person=new Student("ZJH",22,18076120,99.0);运行类型
people[2]=new Student("nihao",222,18076121,100);
people[3]=new Teacher("milan",100,1000);
people[4]=new Teacher("ggg",55,80000);
for ( int i = 0; i < people.length; i++) {
//以下为调用子类重写的方法,利用动态绑定机制
System.out.println(people[i].say());
//以下为通过父类调用子类特有的方法
if(people[i] instanceof Student ){
((Student)people[i]).study();
// Student student = (Student)people[i];
// student.study();
}else if(people[i] instanceof Teacher){
((Teacher)people[i]).teach();
// Teacher teacher = (Teacher)people[i];
// teacher.teach();
}else{
System.out.println("请重新输入");
}
}
//向上引用 Animal animal = new Cat();
// people[1].teach();//错误,因为Personl类中没有teach方法,编译类型不通过,
// 采用向下转型的方法 Cat cat = (Cat)animal
}
}
主方法,注意数组里放置的是对象,注意用多态来解决调用子类重写的方法(动态绑定机制)和调用子类特有的方法的问题(向下转型)



