物件轉型是繼承體系裡最容易踩坑的一環。方向不同,行為也完全不同。
用父類別的型別去指向子類別物件,這是天生安全的,編譯器不會有意見。代價是:你只能透過父類別宣告的方法來操作它,子類別新增的方法看不到;而如果被呼叫的方法被子類別覆寫過,執行的仍然是子類別的方法體——這正是多型的意義。
反過來把父類別型別硬轉成子類別,麻煩就來了:編譯期完全不會報錯,錯誤要等到執行期才以 ClassCastException 爆發。這是為什麼向下轉型前必須先用 instanceof 確認。
package com.han;
public class Test {
int[] a;
int b = 10;
public Test(){
int[] a = {8, 9};
try{
System.out.println(a[0]);
} catch(ArrayIndexOutOfBoundsException e){
String strFile = e.getMessage();
System.out.println(strFile);
new InnerClass();
}
}
void testException() { }
void testOwned(){
System.out.println("It is Test's own method.");
}
void test1() {
a = new int[]{1, 2, 3};
a[2] = b;
System.out.println(a[2]);
}
public static void main(String[] args) {
Test t = new Test();
t.test1();
for(int e : t.a){
System.out.println(e);
}
}
class InnerClass{
InnerClass(){
System.out.println("OK");
}
}
}
package com.han;
/**
* @author Gaowen HAN
*/
public class Test2 extends Test{
@Override
void test1(){
System.out.println("This is a overriding.");
}
void newMethodTest2(){
System.out.println("This is a new method for Test2.");
}
public static void main(String[] args) {
Test2 t1 = new Test2();
t1.testOwned();
t1.newMethodTest2();
t1.b = 11;
t1.test1();
for(int e : t1.a){
System.out.println(e);
}
}
}
package com.han;
public class Test3 {
public static void main(String[] args) {
@SuppressWarnings("unused")
Test2 t2 = (Test2) new Test();
// 執行期報錯:
// Exception in thread "main" java.lang.ClassCastException:
// com.han.Test cannot be cast to com.han.Test2
// System.out.println(t2.b);
}
}
把 new Test() 換成 new Test2(),同一行轉型就安然無事——可見問題不在語法,而在物件真正的型別。
Java 1.5 之後引入的泛型機制,把型別檢查提前到編譯階段,既減少了強制轉型的代碼量,也讓集合的型別安全得到保證。若確實需要向下轉型,先用 instanceof 判斷引用究竟指向哪個子類別,再動手轉。