package com.leo.polyArr;
// 父类
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 = " + name + " age = "+ age;
}
}
package com.leo.polyArr;
public class Student extends Person{
private double score;
public Student(String name, int age, double score) {
super(name, age);
this.score = score;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
@Override
public String say() {
return "Student " + super.say() + "score = " + score;
}
public void study() {
System.out.println("学生在学习");
}
}
package com.leo.polyArr;
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 String say() {
return "Teacher " + super.say() + "salary = " + salary;
}
public void teach() {
System.out.println("老师在上课");
}
}
package com.leo.polyArr;
public class Poly {
public static void main(String[] args) {
Person[] persons = new Person[5];
persons[0] = new Person("Leo", 30);
persons[1] = new Student("Mike", 20, 100);
persons[2] = new Student("John", 22,90);
persons[3] = new Teacher("Scott", 35,10000);
persons[4] = new Teacher("King", 40,20000);
for (int i = 0; i < persons.length; i++) {
System.out.println(persons[i].say());
if (persons[i] instanceof Student) {
Student student = (Student)persons[i];
student.study();
} else if(persons[i] instanceof Teacher) {
Teacher teacher = (Teacher)persons[i];
teacher.teach();
} else {
System.out.println("你的类型错误,请检查");
}
}
}
}