歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java 向上轉型和向下轉型

Java 向上轉型和向下轉型

日期:2017/3/1 10:35:50   编辑:Linux編程

Java 向上轉型後不能使用子類中的新方法,對於使用被重寫的方法名時還是用重寫後的方法體(即子類中的方法體)。

Java 向下轉型運行時會報錯(注意並不是int與char之間的轉換)。但是問題的關鍵是編譯時不會報錯! 詳見具體運行實例:

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

[java]
  1. package com.han;
  2. /**
  3. * @author Gaowen HAN
  4. *
  5. */
  6. public class Test2 extends Test{
  7. @Override
  8. void test1(){
  9. System.out.println("This is a overriding.");
  10. }
  11. void newMethodTest2(){
  12. System.out.println("This is a new method for Test2.");
  13. }
  14. public static void main(String[] args) {
  15. Test2 t1=new Test2();
  16. t1.testOwned();
  17. t1.newMethodTest2();
  18. t1.b=11;
  19. t1.test1();
  20. for(int e:t1.a){
  21. System.out.println(e);
  22. }
  23. }
  24. }
[java]
  1. package com.han;
  2. public class Test3 {
  3. /**
  4. * @param args
  5. */
  6. public static void main(String[] args) {
  7. @SuppressWarnings("unused")
  8. Test2 t2=(Test2) new Test();//運行時報錯Exception in thread "main" java.lang.ClassCastException: com.han.Test cannot be cast to com.han.Test2
  9. //System.out.println(t2.b);
  10. }
  11. }
所以為了避免向下轉型帶來的問題,Java 1.5後引入了泛型機制,不僅使得編程人員可以少寫某些代碼,並且保證了編譯時的類安全檢查。
而對於向上轉型後則是可以用instanceof關鍵字來判斷對象引用的到底是哪個子類。
Copyright © Linux教程網 All Rights Reserved