Java 中父類和子類具有相同的資料成員


父類可以持有對父物件和子物件的引用。如果父類變數持有子類的引用,並且該值在兩個類中都存在,通常,該引用屬於父類變數。這是由於 Java 中的執行時多型特性。

示例

以下是一個示例:

 即時演示

class Demo_base {
   int value = 1000;
   Demo_base() {
      System.out.println("This is the base class constructor");
   }
}
class Demo_inherits extends Demo_base {
   int value = 10;
   Demo_inherits() {
      System.out.println("This is the inherited class constructor");
   }
}
public class Demo {
   public static void main(String[] args) {
      Demo_inherits my_inherited_obj = new Demo_inherits();
      System.out.println("In the main class, inherited class object has been created");
      System.out.println("Reference of inherited class type :" + my_inherited_obj.value);
      Demo_base my_obj = my_inherited_obj;
      System.out.println("In the main class, parent class object has been created");
      System.out.println("Reference of base class type : " + my_obj.value);
   }
}

輸出

This is the base class constructor
This is the inherited class constructor
In the main class, inherited class object has been created
Reference of inherited class type :10
In the main class, parent class object has been created
Reference of base class type : 1000

解釋

一個名為“Demo_base”的類包含一個整數值和一個列印相關訊息的建構函式。另一個名為“Demo_inherits”的類成為父類“Demo_base”的子類。這意味著“Demo_inherits”類擴充套件到基類“Demo_base”。

在這個類中,為同一個變數定義了另一個值,並且定義了子類的建構函式,其中包含要在螢幕上列印的相關訊息。一個名為 Demo 的類包含 main 函式,在該函式中,建立了子類的例項,並在螢幕上列印了其關聯的整數值。透過建立例項並訪問其關聯的值並在螢幕上列印它,對父類也執行了類似的過程。

更新於:2020年9月14日

12K+ 瀏覽量

啟動你的 職業生涯

透過完成課程獲得認證

開始
廣告