When do I use super()? When do I use super()? java java

When do I use super()?


Calling exactly super() is always redundant. It's explicitly doing what would be implicitly done otherwise. That's because if you omit a call to the super constructor, the no-argument super constructor will be invoked automatically anyway. Not to say that it's bad style; some people like being explicit.

However, where it becomes useful is when the super constructor takes arguments that you want to pass in from the subclass.

public class Animal {   private final String noise;   protected Animal(String noise) {      this.noise = noise;   }   public void makeNoise() {      System.out.println(noise);   }}public class Pig extends Animal {    public Pig() {       super("Oink");    }}


super is used to call the constructor, methods and properties of parent class.


You may also use the super keyword in the sub class when you want to invoke a method from the parent class when you have overridden it in the subclass.

Example:

public class CellPhone {    public void print() {        System.out.println("I'm a cellphone");    }}public class TouchPhone extends CellPhone {    @Override    public void print() {        super.print();        System.out.println("I'm a touch screen cellphone");    }    public static void main (strings[] args) {        TouchPhone p = new TouchPhone();        p.print();    }}

Here, the line super.print() invokes the print() method of the superclass CellPhone. The output will be:

I'm a cellphoneI'm a touch screen cellphone