Java中物件向下轉換的規則


在Java中,向下轉換是將父類物件轉換為子類物件的過程。我們需要顯式地執行此轉換。這與我們在基本型別轉換中所做的非常相似。

在這篇文章中,我們將學習向下轉換以及在Java中向下轉換物件必須遵循的規則。

Java中的物件向下轉換

前面我們討論過向下轉換與型別轉換有些相似。然而,也存在一些差異。首先,我們只能對基本資料型別進行型別轉換;其次,它是一個不可逆的操作,即在型別轉換中我們直接操作值,如果我們更改一次值,我們就無法恢復它。另一方面,在向下轉換過程中,原始物件不會改變,只有它的型別改變了。

向下轉換的必要性

例如,假設有兩個類,一個是超類,另一個是它的子類。在這裡,子類包含一些其超類想要使用的特性。在這種情況下,向下轉換就出現了,它允許我們訪問子類對超類的成員變數和方法。

語法

nameOfSubclass nameOfSubclassObject = (nameOfSubclass) nameOfSuperclassObject; 

雖然這個語法看起來很簡單,但我們很多人在編寫這個語法時可能會出錯。此外,我們不能像在下一個例子中那樣直接向下轉換物件。如果我們這樣做,編譯器將丟擲“ClassCastException”。

示例1

下面的例子說明了提供錯誤的向下轉換語法可能導致的結果。為此,我們將定義兩個類,並嘗試使用錯誤的語法向下轉換超類物件。

class Info1 {  
// it is the super class
   void mesg1() { 
      System.out.println("Tutorials Point"); 
   }
} 
class Info2 extends Info1 {
// inheriting super class
   void mesg2() { 
      System.out.println("Simply Easy Learning"); 
   }
} 
public class Down {
   public static void main(String[] args) { 
      Info2 info2 = (Info2) new Info1(); 
      // Wrong syntax of downcasting
      // calling both methods using sub class object
      info2.mesg1(); 
      info2.mesg2(); 
   } 
}

輸出

Exception in thread "main" java.lang.ClassCastException: class Info1 cannot be cast to class Info2 (Info1 and Info2 are in unnamed module of loader 'app')
   at Down.main(Down.java:13)

示例2

下面的例子演示瞭如何正確地執行物件向下轉換。為此,我們將建立兩個類,然後定義一個引用子類的超類物件。最後,我們使用正確的向下轉換語法。

class Info1 {
// it is the super class
   void mesg1() { 
      System.out.println("Tutorials Point"); 
   }
} 
class Info2 extends Info1 {  
// inheriting super class
   void mesg2() { 
      System.out.println("Simply Easy Learning"); 
   }
} 
public class Down { 
   public static void main(String[] args) { 
      // object of super class refers to sub class
      Info1 info1 = new Info2(); 
      // performing downcasting
      Info2 info2 = (Info2) info1;
      // calling both methods using object of sub class 
      info2.mesg1(); 
      info2.mesg2(); 
   } 
}

輸出

Tutorials Point
Simply Easy Learning

結論

還有一個名為向上轉換的概念用於修改物件。在這個過程中,子類物件被轉換為超類物件。它可以隱式地完成。向上轉換和向下轉換這兩個概念一起被稱為物件轉換。在這篇文章中,我們透過例子討論了物件向下轉換。

更新於:2023年5月15日

650 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.