例子
Person类(父类)
package poly.array;
public class Person {
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String say(){
return "name = " + this.name + "\t" + "age = " + this.age;
}
}
Student类(子类)
package poly.array;
public class Student extends Person{
private int score;
public Student() {
}
public Student(String name, int age, int score) {
super(name, age);
this.score = score;
}
@Override
public String say() {
return super.say() + "\t" + "score = " + score;
}
}
Teacher类(子类)
package poly.array;
public class Teacher extends Person{
private int salary;
public Teacher() {
}
public Teacher(String name, int age, int salary) {
super(name, age);
this.salary = salary;
}
@Override
public String say() {
return super.say() + "\t" + "salary = " + this.salary;
}
}
package poly.array;
public class Test {
public static void main(String[] args) {
Person[] people = new Person[5];
people[0] = new Student("amei",21,90);
people[1] = new Person("aha",20);
people[2] = new Student("marry",30,89);
people[3] = new Teacher("socro",40,30000);
people[4] = new Teacher("madalam",79,100000);
for (Person p:people
) {
System.out.println(p.say());
}
}
}
结果
name = amei age = 21 score = 90
name = aha age = 20
name = marry age = 30 score = 89
name = socro age = 40 salary = 30000
name = madalam age = 79 salary = 100000
升级:如何调用子类特有方法,比如Teacher有一个teach,Student有一个study怎么调用?
for (Person p:people
) {
System.out.println(p.say());
if (p instanceof Student)
((Student) p).study();
else if (p instanceof Teacher)
((Teacher) p).teach();
}
结果
name = amei age = 21 score = 90
ameiis studying…
name = aha age = 20
name = marry age = 30 score = 89
marryis studying…
name = socro age = 40 salary = 30000
socrois teaching…
name = madalam age = 79 salary = 100000
madalamis teaching…