What is the super() construct of a constructor in Java?

Java 8Object Oriented ProgrammingProgramming

The super keyword is similar to this keyword. Following are the scenarios where a super keyword is used.

  • It is used to differentiate the members of superclass from the members of the subclass if they have same names.
  • It is used to invoke the superclass constructor from the subclass.

Whenever you want to call the constructor of the superclass from a method or another constructor you can do so as:

Example

class Person {
   Person(String name) {
      System.out.println("Hello "+ name);
   }
}

class Student extends Person {
   Student(String name) {
      super(name);
   }

   public static void main(String args[]) {
      Student st = new Student("Ram");
   }
}

Output

Hello Ram
raja
Published on 29-Dec-2017 09:24:46
Advertisements