在Java中,當子類物件賦值給父類物件時會發生什麼?
在Java中,將一種資料型別轉換為另一種資料型別的過程稱為型別轉換。
如果將更高資料型別轉換為較低資料型別,則稱為縮小轉換(將更高資料型別的值賦給較低資料型別的變數)。
char ch = (char)5;
如果將較低資料型別轉換為更高資料型別,則稱為擴充套件轉換(將較低資料型別的值賦給更高資料型別的變數)。
Int i = 'c';
類似地,您也可以將一個類型別的物件轉換為其他型別。但這兩個類必須存在繼承關係。然後,
如果將父類轉換為子類型別,則在引用方面稱為縮小轉換(子類引用變數持有父類物件)。
Sub sub = (Sub)new Super();
如果將子類轉換為父類型別,則在引用方面稱為擴充套件轉換(父類引用變數持有子類物件)。
Super sup = new Sub();
將子類物件賦值給父類變數
因此,如果將子類物件的賦值給父類的引用變數,則子類物件將轉換為父類型別,此過程稱為擴充套件轉換(在引用方面)。
但是,使用此引用只能訪問父類的成員,如果嘗試訪問子類成員,則會生成編譯時錯誤。
示例
在下面的Java示例中,我們有兩個類,分別是Person和Student。Person類有兩個例項變數name和age,以及一個例項方法displayPerson(),用於顯示姓名和年齡。
Student類繼承Person類,除了繼承的name和age之外,它還有兩個變數branch和student_id。它有一個方法displayData(),用於顯示所有四個值。
在main方法中,我們將子類物件賦值給父類引用變數
class Person{
public String name;
public 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: "+super.name);
System.out.println("Age: "+super.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
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP