如何在Java中將子類變數轉換為超類型別?
繼承是兩個類之間的關係,其中一個類繼承另一個類的屬性。這種關係可以使用`extends`關鍵字定義為:
public class A extends B{
}
繼承屬性的類稱為子類或子類,而其屬性被繼承的類稱為超類或父類。
在繼承中,超類成員的副本會在子類物件中建立。因此,使用子類物件,您可以訪問這兩個類的成員。
將子類變數轉換為超類型別
您可以直接將子類變數(值)賦值給超類變數。簡而言之,超類引用變數可以持有子類物件。但是,使用此引用只能訪問超類成員,如果嘗試訪問子類成員,則會生成編譯時錯誤。
示例
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 Sample extends Person {
public String branch;
public int Student_id;
public Sample(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 Person("Krishna", 20);
//Converting super class variable to sub class type
Sample sample = new Sample("Krishna", 20, "IT", 1256);
person = sample;
person.displayPerson();
}
}輸出
Data of the Person class: Name: Krishna Age: 20
示例
class Super{
public Super(){
System.out.println("Constructor of the Super class");
}
public void superMethod() {
System.out.println("Method of the super class ");
}
}
public class Test extends Super {
public Test(){
System.out.println("Constructor of the sub class");
}
public void subMethod() {
System.out.println("Method of the sub class ");
}
public static void main(String[] args) {
Super obj = new Test();
obj.superMethod();
}
}輸出
Constructor of the Super class Constructor of the sub class Method of the super class
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP