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?
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.
super() is used to call Base class's(Parent class's) constructor.
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.
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.
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 :-)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With