这里是比较经典的例子,Son类继承Father
public class Father {
public static void main(String[] args) {
Father father = new Son();
Son son = (Son) father;
}
void b(){
System.out.print(1);
}
}
class Son extends Father{
void a(){}
void b(){
System.out.print(33);
}
}
class SonTwo extendS Father{
}
这行就是向上转型
Father father = new Son();
father使用时是Father类型,可以在下面向下转型的代码中把类型转换(Son)删去,查看IDEA报错信息进行验证; 在内存中本质为Son类型,可以调用getclass方法验证,这也是为什么father能向下转型为Son类型的原因。
向上转型的目标是father,子类重写父类方法后,例如此时father调用(father.b)b方法,默认调用子类重写的b方法,得到结果为33而不是1;
向上转型后father作为Father类型使用,所以使用时无法调用Son中Son自身拥有而父类没有的方法,若要调用Son中方法可以参考下面这行代码调用
((Son) father).a();
这行就是向下转型
Son son = (Son) father;
向下转型的目标是father,可理解为把father恢复了Son的类型的使用,可以理解为:(Son) father相当于Son father = new Son;
但是运行这行代码以后father仍是使用时为Father类型,内存中为Son类型;即(Son)father为暂时恢复father为Son类型
如果父类为抽象类可以通过这个方法调用父类的非抽象方法。
也就是通过这个方式的应用作用之一就是可以调用父类中所有未被子类重写的方法,同时可以通过向下转型调用子类中所有的方法
还有一种就是在引用数据类型中的应用。
————————————————————————————
——更新笔记
————————————————————————————
这样IDEA不运行不编译不会报错,但是一编译或运行会报ClassCastException异常,属于运行时异常,是JVM在检测到两个类型间转换不兼容时引发的运行时异常。
Father father = new Son();
SonTwo sontwo = (SonTwo) father;
参考:
https://blog.csdn.net/m0_37695902/article/details/120161828
https://blog.csdn.net/lisainan66/article/details/133135939
https://blog.csdn.net/Allen_forv/article/details/80771650
https://blog.csdn.net/qq_44147882/article/details/114334255
https://blog.csdn.net/chenssy/article/details/12785831
https://blog.csdn.net/chenssy/article/details/14111307