When do I use super()?

JavaInheritanceSuper

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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

Solution 3 - Java

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

Solution 4 - Java

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()

Solution 5 - Java

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

Solution 6 - Java

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.

Solution 7 - Java

Solution 8 - Java

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.

Solution 9 - Java

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

Solution 10 - Java

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:

https://stackoverflow.com/questions/154577/polymorphism-vs-overriding-vs-overloading/39532917#39532917

Solution 11 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionmuttley91View Question on Stackoverflow
Solution 1 - JavaMark PetersView Answer on Stackoverflow
Solution 2 - JavaZain ShaikhView Answer on Stackoverflow
Solution 3 - JavaDhiraj ShekarView Answer on Stackoverflow
Solution 4 - JavaTartanLlamaView Answer on Stackoverflow
Solution 5 - JavaJonView Answer on Stackoverflow
Solution 6 - JavaAHungerArtistView Answer on Stackoverflow
Solution 7 - JavaBen GrootView Answer on Stackoverflow
Solution 8 - Java0xCAFEBABEView Answer on Stackoverflow
Solution 9 - JavarobevView Answer on Stackoverflow
Solution 10 - JavaRavindra babuView Answer on Stackoverflow
Solution 11 - JavaShiva BorusuView Answer on Stackoverflow