This question already has an answer here:
- Is it unnecessary to put super() in constructor? 6 answers
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