Java 中的父類引用變數可以持有子類的物件嗎?


是的,父類引用變數實際上可以持有子類物件,這是物件的多型性(將較低資料型別轉換為較高資料型別)。

但是,使用此引用,您只能訪問父類的成員,如果您嘗試訪問子類成員,則會生成編譯時錯誤。

示例

在下面的 Java 示例中,我們有兩個類,分別是 Person 和 Student。Person 類有兩個例項變數 name 和 age,以及一個例項方法 displayPerson(),它顯示姓名和年齡。

Student 類擴充套件了 Person 類,除了繼承的 name 和 age 之外,它還有兩個變數 branch 和 student_id。它有一個方法 displayData(),顯示所有四個值。

在 main 方法中,我們使用父類引用變數賦值子類物件。

class Person{
   private String name;
   private int age;
   public Person(String name, int age){
      this.name = name;
      this.age = age;
   }
   public void displayPerson() {
      System.out.println("Data of the Person class: ");
      System.out.println("Name: "+this.name);
      System.out.println("Age: "+this.age);
   }
}
public class Student extends Person {
   public String branch;
   public int Student_id;
   public Student(String name, int age, String branch, int Student_id){
      super(name, age);
      this.branch = branch;
      this.Student_id = Student_id;
   }
   public void displayStudent() {
      System.out.println("Data of the Student class: ");
      System.out.println("Name: "+this.name);
      System.out.println("Age: "+this.age);
      System.out.println("Branch: "+this.branch);
      System.out.println("Student ID: "+this.Student_id);
   }
   public static void main(String[] args) {
      Person person = new Student("Krishna", 20, "IT", 1256);
      person.displayPerson();
   }
}

輸出

Data of the Person class:
Name: Krishna
Age: 20

訪問子類方法

當您將子類物件賦值給父類引用變數,並使用此引用嘗試訪問子類成員時,將生成編譯時錯誤。

示例

在這種情況下,如果您將 Student 物件賦值給 Person 類的引用變數:

Person person = new Student("Krishna", 20, "IT", 1256);

使用此引用,您只能訪問父類的方法,即 displayPerson()。如果您嘗試訪問子類方法,即 displayStudent(),則會生成編譯時錯誤。

因此,如果您將前面程式的 main 方法替換為以下內容,則會生成編譯時錯誤。

public static void main(String[] args) {
   Person person = new Student("Krishna", 20, "IT", 1256);
   person.displayStudent();
}

編譯時錯誤

Student.java:33: error: cannot find symbol
   person.dispalyStudent();
        ^
   symbol: method dispalyStudent()
   location: variable person of type Person
1 error

更新於:2020年7月2日

3K+ 瀏覽量

啟動您的職業生涯

完成課程獲得認證

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