This question already has an answer here:
I always thought that when creating an object with a sub-class, we need to explicitly use super(arguments list)
to call the constructor of the super class. However I did an experiment and realize that even without using the super()
, the super class's constructor will be called automatically. Is this true?
If this is true, when is super()
redundant and when it is not?
class Parent
{
public Parent()
{
System.out.println("Super Class");
}
}
class Child extends Parent
{
public Child()
{
super(); //Is this redundant?
System.out.println("Sub Class");
}
}
public class TestClass
{
public static void main(String[] args)
{
new Child();
}
}
OUTPUT (With super();
in Child Class):
Super Class
Sub Class
OUTPUT (Without super();
in Child Class):
Super Class
Sub Class
By default
super()
is added in all sub-class so don't need to call it explicitly.The default behavior can be overridden by calling overloaded constructor of super class using
super(args)
or overloaded constructor of same class usingthis(args)
.Suppose super class doesn't have no-argument constructor and you have created other constructor, in that case you have to call
super(args)
explicitly to resolve compile time error.When in doubt, always consult the specification: