How to call the constructor of a superclass from a constructor in java?


Whenever you inherit/extend a class, a copy of superclass’s members is created in the subclass object and thus, using the subclass object you can access the members of both classes.

Example

In the following example we have a class named SuperClass with a method with name demo(). We are extending this class with another class (SubClass).

Now, you create an object of the subclass and call the method 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();
   }
}

Output

demo method

Super class’s Constructor in inheritance

In inheritance constructors are not inherited. You need to call them explicitly using the super keyword.

If a Super class have parameterized constructor. You need to accept these parameters in the sub class’s constructor and within it, you need to invoke the super class’s constructor using “super()” as −

public Student(String name, int age, String branch, int Student_id){
   super(name, age);
   this.branch = branch;
   this.Student_id = Student_id;
}

Example

Following java program demonstrates how to call a super class’s constructor from the constructor of the sub class using the super keyword.

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();
   }
}

Output

Data of the Person class:
Name: Krishna
Age: 20

Updated on: 01-Aug-2019

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements