说明
《第一行代码 JAVA》的 4.5 多态性 (p224)提到:“ 多态性在开发中可以体现为以下两个方面。方法的多态性:重载、复写:…… 对象的多态性:父子类对象的转换…… ”
父子类相互转型的格式是
- 父类 父类对象 = 子类实例; //向上转型,自动转换
- 子类 子类对象 = (子类) 父类实例; //向下转型,强制转换
其中 子类 → 父类 的向上转型是自动完成的,不会存在问题;但是 父类 → 子类 的向下转型过程中,容易出现 ClassCastException 的类转换异常,只有先向上转型再向下转型的过程(子类 → 父类 → 子类)才能避免这一异常警报。
程序说明如下:
1. 创建父类 A
public class A {
public void print(){
System.out.println("A: method");
}
}
2. 创建子类 B
public class B extends A {
public void print(){
System.out.println("B: method");
}
public void funB(){
System.out.println("B: extended method");
}
}
3. 调用 A 和 B 的方法
public class Temp {
public static void main(String[] args){
A a = new A();
a.print(); //调用父类的print方法
B b = new B();
b.funB(); //调用子类的funB方法
A temp0 = b; //向上转型(子→父)
temp0.print(); //调用对象b对应的类方法
B temp1 = (B) a; //强制向下转型(父→子)
B temp2 = (B) temp0; //向下转型(子→父→子)
temp2.funB();
}
}
4. 结果
A: method [调用父类的print方法]
B: extended method [调用子类的funB方法]
B: method [向上转型(子→父)并调用对象b对应的类方法]
Exception in thread "main" java.lang.ClassCastException: temp20200221.A cannot be cast to temp20200221.B [强制向下转型(父→子)]
B: extended method [向下转型(子→父→子)]