public abstract class Person { private String name; public Person(String name) { this.name = name; } public abstract String getDescription(); public String getName() { return name; } }
public class Student extends Person { private String major; public Student(String name, String major) { super(name); this.major = major; } @Override public String getDescription() { return "a student majoring in" + major; } }
Person[] people = new Person[2]; Person[0] = new Student(...); System.out.println(people[0].getName() + "," + people[0].getDescription());
有人可能对 people[0].getDescription() 感到疑惑。请牢记,由于不能构造Person的对象,所以变量永远不会引用Person对象,而是引用具体子类对象,这些对象都定义了getDescription方法。同时,编译器也只允许调用在类中声明的方法。