把超类对象转换为子类对象叫做向下转换
public class TyoeCompatibility {
public static void main(String[] args) {
// TODO Auto-generated method stub
Student s = new GradStudent();
GradStudent g = new GradStudent();
/* int x = s.getID(); this method is incorrect because getID doesn't exist in Student class
which results in compile-time error */
int y = g.getID();
int x = ((GradStudent)s).getID();
}
}
在此例中getID()方法只出现在Student子类GradStudent类里,因此Student类的s调用getID()会出现compile-time error。可以通过向下转换把s类型转换为GradStudent
注意向下转换时必须写为((GradStudent)s).getID(),如果写为(GradStudent)s.getID()依然报错,因为 . 的优先级大于 (转换)
AP在此处考法:不会直接考类型转换,而是给一个没有转换的错误示例,要判断出这是一个compiler-time error