Java 向上转型和向下转型


Java 向上转型后不能使用子类中的新方法,对于使用被重写的方法名时还是用重写后的方法体(即子类中的方法体)。

Java 向下转型运行时会报错(注意并不是int与char之间的转换)。但是问题的关键是编译时不会报错! 详见具体运行实例:

[java]
  1. package com.han;  
  2.   
  3. public class Test {  
  4.     int[] a;  
  5.     int b=10;  
  6.     public Test(){  
  7.         int[] a={8,9};  
  8.         try{  
  9.             System.out.println(a[0]);  
  10.         }catch(ArrayIndexOutOfBoundsException e){  
  11.             String strFile=e.getMessage();  
  12.             System.out.println(strFile);  
  13.             new InnerClass();  
  14.         }  
  15.     }  
  16.      void testException() {  
  17.     }  
  18.     void testOwned(){  
  19.         System.out.println("It is Test's own method.");  
  20.     }  
  21.     void test1() {  
  22.          a=new int[]{1,2,3};  
  23.          a[2]=b;  
  24.          System.out.println(a[2]);  
  25.         }  
  26.     public static void main(String[] args) {  
  27.         Test t=new Test();  
  28.         t.test1();  
  29.         for(int e:t.a){  
  30.             System.out.println(e);  
  31.         }  
  32.     }  
  33.   
  34.     class InnerClass{  
  35.         InnerClass(){  
  36.             System.out.println("OK");  
  37.         }  
  38.           
  39.     }  
  40. }  

[java]
  1. package com.han;  
  2.   
  3. /** 
  4.  * @author Gaowen HAN 
  5.  * 
  6.  */  
  7. public class Test2 extends Test{  
  8.       
  9.     @Override  
  10.     void test1(){  
  11.         System.out.println("This is a overriding.");  
  12.     }  
  13.     void newMethodTest2(){  
  14.         System.out.println("This is a new method for Test2.");  
  15.     }  
  16.   
  17.     public static void main(String[] args) {  
  18.         Test2 t1=new Test2();  
  19.         t1.testOwned();  
  20.         t1.newMethodTest2();  
  21.         t1.b=11;  
  22.         t1.test1();  
  23.         for(int e:t1.a){  
  24.             System.out.println(e);  
  25.         }  
  26.     }  
  27. }  
[java]
  1. package com.han;  
  2.   
  3. public class Test3 {  
  4.   
  5.     /** 
  6.      * @param args 
  7.      */  
  8.     public static void main(String[] args) {  
  9.         @SuppressWarnings("unused")  
  10.         Test2 t2=(Test2) new Test();//运行时报错Exception in thread "main" java.lang.ClassCastException: com.han.Test cannot be cast to com.han.Test2   
  11.         //System.out.println(t2.b);   
  12.     }  
  13.   
  14. }  
所以为了避免向下转型带来的问题,Java 1.5后引入了泛型机制,不仅使得编程人员可以少写某些代码,并且保证了编译时的类安全检查。
而对于向上转型后则是可以用instanceof关键字来判断对象引用的到底是哪个子类。

相关内容