多态数组的简单代码教学
package com.hspedu.polrArr;
public class PloyArray {
public static void main(String[] args) {
Person[] persons = new Person[5];
persons[0] = new Person("jack", 20);
persons[1] = new Student("smith", 21,100);
persons[2] = new Student("alan",22,60);
persons[3] = new Teacher("王老师" ,40,2000);
persons[4] = new Teacher("李老师",45,2500);
for (int i = 0; i < persons.length; i++) {
System.out.println(persons[i].say());
if (persons[i] instanceof Student){
((Student)persons[i]).study();
} else if (persons[i] instanceof Teacher){
((Teacher)persons[i]).teach();
} else {
System.out.println("父类Person");
}
}
}
}
package com.hspedu.polrArr;
public class PloyArray {
public static void main(String[] args) {
Person[] persons = new Person[5];
persons[0] = new Person("jack", 20);
persons[1] = new Student("smith", 21,100);
persons[2] = new Student("alan",22,60);
persons[3] = new Teacher("王老师" ,40,2000);
persons[4] = new Teacher("李老师",45,2500);
for (int i = 0; i < persons.length; i++) {
System.out.println(persons[i].say());
if (persons[i] instanceof Student){
((Student)persons[i]).study();
} else if (persons[i] instanceof Teacher){
((Teacher)persons[i]).teach();
} else {
System.out.println("父类Person");
}
}
}
}
package com.hspedu.polrArr;
public class Person {
private String name;
private int age;
public Person(String person, int age) {
this.name = person;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String person) {
this.name = person;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String say() {
return "姓名 " + name + " 年龄 " + age;
}
}
package com.hspedu.polrArr;
import com.sun.org.apache.regexp.internal.RE;
public class Student extends Person{
private double score;
public Student(String person, int age, double score) {
super(person, age);
this.score = score;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
public String say(){
return super.say() + " 成绩 " + score;
}
public void study() {
System.out.println("学生" + getName() + "正在学习中....");
}
}
package com.hspedu.polrArr;
public class Teacher extends Person {
private double salary;
public Teacher(String person, int age, double salary) {
super(person, 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("老师" + getName() + "正在授课....");
}
}