如何从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("Person类的数据: ");
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();
}
}输出结果
Person类的数据: Name: Krishna Age: 20