When do I use super()?

muttley91 picture muttley91 · Nov 3, 2010 · Viewed 170.4k times · Source

I'm currently learning about class inheritance in my Java course and I don't understand when to use the super() call?

Edit:
I found this example of code where super.variable is used:

class A
{
    int k = 10;
}

class Test extends A
{
    public void m() {
        System.out.println(super.k);
    }
}

So I understand that here, you must use super to access the k variable in the super-class. However, in any other case, what does super(); do? On its own?

Answer

Mark Peters picture Mark Peters · Nov 3, 2010

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