Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling super()

Tags:

java

When do you call super() in Java? I see it in some constructors of the derived class, but isn't the constructors for each of the parent class called automatically? Why would you need to use super?

like image 262
SIr Codealot Avatar asked Apr 13 '10 20:04

SIr Codealot


People also ask

What does calling the super () method do?

Definition and Usage It is used to call superclass methods, and to access the superclass constructor. The most common use of the super keyword is to eliminate the confusion between superclasses and subclasses that have methods with the same name.

Is super () a call?

super() is used to call Base class's(Parent class's) constructor.

Do you need to call super ()?

However, using super() is not compulsory. Even if super() is not used in the subclass constructor, the compiler implicitly calls the default constructor of the superclass.

What is the difference between calling super and calling super ()?

When you call super with no arguments, Ruby sends a message to the parent of the current object, asking it to invoke a method with the same name as where you called super from, along with the arguments that were passed to that method. On the other hand, when called with super() , it sends no arguments to the parent.


2 Answers

If you provide a class like this:

public class Foo { } 

or this:

public class Foo() {     public Foo()     {     } } 

the compiler will generate code for this:

public class Foo() {     public Foo()     {         super();     } } 

So, strictly speaking, the call to "super()" is always there.

In practice you should only call "super(...)" where there are parameters you want to pass to the parent constructor.

It isn't wrong to call "super()" (with no parameters) but people will laugh at you :-)

like image 146
TofuBeer Avatar answered Sep 29 '22 15:09

TofuBeer


You would need to use super() in a case like this:

public class Base {    public Base(int foo) {    } }  public class Subclass extends Base {    public Subclass() {       super(15);    } } 

This is a very contrived example, but the only time that you need to call super() is if you're inheriting from a class that doesn't provided a default, parameterless constructor. In this cases you need to explicitly call super() from the constructor of your subclass, passing in whatever parameters you need to satisfy the base class's constructor. Also, the call to super() must be the first line of your inherited class's constructor.

like image 23
Skrud Avatar answered Sep 29 '22 15:09

Skrud