What happens if we call "super()" in a constructor without extending any class, in java?

Java 8Object Oriented ProgrammingProgramming

A super keyword is a reference of the superclass object in Java. Using this, you can invoke the instance methods constructors and, variables, of a superclass.

Calling the constructor of a superclass

You can call the constructor of a superclass from the subclass’s constructor.

Example

Consider the following example, it has two classes SuperClass class and SubClass where the SubClass extends the SuperClass. The superclass has a parameterized constructor, we are invoking it from the subclass using the "super" keyword.

 Live Demo

class SuperClass{
   SuperClass(int data){
      System.out.println("Superclass's constructor: "+data);
   }
}
public class SubClass extends SuperClass{
   SubClass(int data) {
      super(data);
   }
   public static void main(String args[]){
      SubClass sub = new SubClass(400);
   }
}

Output

Superclass's constructor: 400

If the SuperClass has a default Constructor there is no need to call it using"super()" explicitly, it will be invoked implicitly.

Example

 Live Demo

class SuperClass{
   SuperClass(){
      System.out.println("Superclass's constructor");
   }
}
public class SubClass extends SuperClass{
   SubClass() {
      //super();
   }
   public static void main(String args[]){
      SubClass sub = new SubClass();
   }
}

Output

Superclass's constructor

If we call "super()" without any superclass

Actually, nothing will be displayed. Since the class named Object is the superclass of all classes in Java. If you call "super()" without any superclass, Internally, the default constructor of the Object class will be invoked (which displays nothing).

 Live Demo

public class Sample {
   Sample() {
      super();
   }
   public static void main(String args[]){
      Sample sub = new Sample();
   }
}

Output

//Nothing will be displayed……
raja
Published on 02-Jul-2019 15:15:20
Advertisements