88

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?

muttley91
  • 12,278
  • 33
  • 106
  • 160
  • 32
    Actually, in this example `super` is not required to reference `k`. `k` can be referenced directly. `super` would only be required to access `A.k` if you declared another field named `k` in `Test` (`Test.k`). – Mark Peters Nov 03 '10 at 19:32

11 Answers11

150

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");
    }
}
Mark Peters
  • 80,126
  • 17
  • 159
  • 190
  • 2
    Suppose a method is overriden in a child class and then again overriden in its child class. ( Multilevel Inheritance) What if we have to call a method of the grandparent and the parent simultaneously into the grandchildren class. How would the super be used? – h8pathak Aug 10 '15 at 13:00
  • 3
    @h8pathak: If you're asking how a child class can bypass its parent's implementation but call the grandparent, that's not possible in Java. – Mark Peters Aug 10 '15 at 14:17
45

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

Zain Shaikh
  • 6,013
  • 6
  • 41
  • 66
25

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 cellphone
I'm a touch screen cellphone
MaxZoom
  • 7,619
  • 5
  • 28
  • 44
Dhiraj Shekar
  • 361
  • 3
  • 5
11

You would use it as the first line of a subclass constructor to call the constructor of its parent class.

For example:

public class TheSuper{
    public TheSuper(){
        eatCake();
    }
}

public class TheSub extends TheSuper{
    public TheSub(){
        super();
        eatMoreCake();
    }
}

Constructing an instance of TheSub would call both eatCake() and eatMoreCake()

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
TartanLlama
  • 63,752
  • 13
  • 157
  • 193
9

When you want the super class constructor to be called - to initialize the fields within it. Take a look at this article for an understanding of when to use it:

http://download.oracle.com/javase/tutorial/java/IandI/super.html

Jonathan Holloway
  • 62,090
  • 32
  • 125
  • 150
  • 4
    As it says in the link, you never *have* to call `super()`, as Java will implicitly add it. But you do have to call `super(args)` if you need a non-default parent constructor. – Michael Brewer-Davis Nov 03 '10 at 19:32
1

You could use it to call a superclass's method (such as when you are overriding such a method, super.foo() etc) -- this would allow you to keep that functionality and add on to it with whatever else you have in the overriden method.

AHungerArtist
  • 9,332
  • 17
  • 73
  • 109
1

Super will call your parent method. See: http://leepoint.net/notes-java/oop/constructors/constructor-super.html

Ben Groot
  • 5,040
  • 3
  • 40
  • 47
1

You call super() to specifically run a constructor of your superclass. Given that a class can have multiple constructors, you can either call a specific constructor using super() or super(param,param) oder you can let Java handle that and call the standard constructor. Remember that classes that follow a class hierarchy follow the "is-a" relationship.

0xCAFEBABE
  • 5,576
  • 5
  • 34
  • 59
0

From oracle documentation page:

If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super.

You can also use super to refer to a hidden field (although hiding fields is discouraged).

Use of super in constructor of subclasses:

Invocation of a superclass constructor must be the first line in the subclass constructor.

The syntax for calling a superclass constructor is

super();  

or:

super(parameter list);

With super(), the superclass no-argument constructor is called. With super(parameter list), the superclass constructor with a matching parameter list is called.

Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error.

Related post:

Polymorphism vs Overriding vs Overloading

Ravindra babu
  • 37,698
  • 11
  • 250
  • 211
0

I just tried it, commenting super(); does the same thing without commenting it as @Mark Peters said

package javaapplication6;

/**
 *
 * @author sborusu
 */
public class Super_Test {
    Super_Test(){
        System.out.println("This is super class, no object is created");
    }
}
class Super_sub extends Super_Test{
    Super_sub(){
       super();
       System.out.println("This is sub class, object is created");
    }
    public static void main(String args[]){
        new Super_sub();
    }
}
0

The first line of your subclass' constructor must be a call to super() to ensure that the constructor of the superclass is called.

robev
  • 1,909
  • 3
  • 23
  • 32
  • Not true. It'll happen automatically. – Mark Peters Nov 03 '10 at 19:38
  • Even if there's no default constructor? How will it know what to pass? – robev Nov 03 '10 at 19:43
  • If there's no default constructor, you need to call `super(some args)`, not `super()`. But the point is, "must" is wrong. One of the super class's constructors is **guaranteed** to be called as long as the class compiles. – Mark Peters Nov 03 '10 at 19:45
  • I didn't make it clear that when I wrote super() I didn't mean a constructor with no parameters, I just didn't feel like writing any. And yes I meant you needed to call it or it won't compile, that's why I said must. – robev Nov 03 '10 at 20:55
  • 2
    Once again, you do NOT need an explicit call to a super constructor if there exists a no-arg constructor in the parent class. A super constructor will **always** be called, whereas your phrasing makes it sound like you're in danger of a super constructor not being called if you don't put `super(...)` in. There is absolutely no danger of that; just danger that it won't compile. – Mark Peters Nov 04 '10 at 14:45