如何在 java 中从构造函数调用超类的构造函数?
java 8object oriented programmingprogramming更新于 2025/9/19 17:48:17
每当您继承/扩展一个类时,都会在子类对象中创建超类成员的副本,因此,使用子类对象,您可以访问两个类的成员。
示例
在下面的例子中,我们有一个名为 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 方法
继承中的超类构造函数
在继承中,构造函数不会被继承。您需要使用 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

