有关向上向下转型
// Student extends Person
Person person = new Student();
实例化Student类,并新建一个Person类的引用变量引用该实例。是谁的实例就是调用谁的构造方法创建对象。
这个对象可以调用Person类的方法,如果方法被子类Student覆写,则调用覆写后的方法。但是不能调用子类Student独有的方法(因为它是Person类的),可以通过向下转型后调用Student类独有的方法。
// 向下转型
Student student = (Student) person;
对象 | 可调用方法范围 |
---|---|
Person person = new Person(); | 父类(Person)方法 |
Student student = new Student(); | 子类(Student)方法 |
Person person = new Student(); | 父类方法,如果被子类覆写过则调用覆写后的方法 |
Student student = (Student) person; | 父类方法,如果被子类覆写过则调用覆写后的方法 | 子类独有方法 |