数组的定义类型为父类类型,里面保存的实际元素为子类元素
public class Ploy_array {
public static void main(String[] args) {
Person[] persons = new Person[5];
persons[0] = new Person("tom",20);
persons[1] = new Student("jack",18,70);
persons[2] = new Student("smith",18,90);
persons[3] = new Teacher("li",65,10000);
persons[4] = new Teacher("wang",35,15000);
// 遍历
for(int i = 0; i < persons.length; i++){
/*类型判断 + 向下转型*/
// 判断运行类型是不是Student
if(persons[i] instanceof Student){
// 方法一 匿名方式调用方法
// ((Student) persons[i]).study();
// 方法二
Student student = (Student)persons[i];
System.out.println(student.study());
}
else if(persons[i] instanceof Teacher){
System.out.println(((Teacher) persons[i]).teach());
}
else if(persons[i] instanceof Person){
System.out.println(((Person) persons[i]).say());
}
else{
System.out.println("类型有误");
}
}
}
}
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 + "\t" + age;
}
}
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;
}
public String say(){
return super.say() +"\t" + score;
}
public String study(){
return getName() + "学生正在学习";
}
}
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() + "\t" + salary;
}
public String teach(){
return getName() + "老师正在授课";
}
}