如何在 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

更新于:01-Aug-2019

5K+ 浏览量

启动你的职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.