Java 向上轉型後不能使用子類中的新方法,對於使用被重寫的方法名時還是用重寫後的方法體(即子類中的方法體)。
Java 向下轉型運行時會報錯(註意並不是int與char之間的轉換)。但是問題的關鍵是編譯時不會報錯! 詳見具體運行實例:
[java]
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");
}
}
}
[java]
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);
}
}
}
[java]
package com.han;
public class Test3 {
/**
* @param args
*/
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);
}
}
所以為瞭避免向下轉型帶來的問題,Java 1.5後引入瞭泛型機制,不僅使得編程人員可以少寫某些代碼,並且保證瞭編譯時的類安全檢查。
而對於向上轉型後則是可以用instanceof關鍵字來判斷對象引用的到底是哪個子類。
摘自 Gaowen_HAN的專欄