如何在 java 中從一個建構函式中呼叫超類的建構函式?
每當你繼承/擴充套件一個類時,超類的成員的副本就會在子類物件中建立,從而,使用子類物件你可以訪問兩個類的成員。
示例
在以下示例中,我們有一個名為 SuperClass 的類,其中一個方法名為 demo()。我們用另一個類(SubClass)擴充套件這個類。
現在,你建立一個子類物件並呼叫方法 demo()。
class SuperClass{
public void demo() {
System.out.println("demo method");
}
}
public class SubClass extends SuperClass {
public static void main(String args[]) {
SubClass obj = new SubClass();
obj.demo();
}
}輸出
demo method
繼承中超類的建構函式
在繼承中,建構函式不會被繼承。你需要使用 super 關鍵字顯式地呼叫它們。
如果一個超類有引數化的建構函式。你需要在子類的建構函式中接受這些引數,並在其中,你需要透過 "super()" 來呼叫超類的建構函式,如下所示 -
public Student(String name, int age, String branch, int Student_id){
super(name, age);
this.branch = branch;
this.Student_id = Student_id;
}示例
下面的 java 程式演示瞭如何使用 super 關鍵字從子類的建構函式中呼叫超類的建構函式。
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: "+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) throws CloneNotSupportedException {
Person person = new Student("Krishna", 20, "IT", 1256);
person.displayPerson();
}
}輸出
Data of the Person class: Name: Krishna Age: 20
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP