Is calling super's constructor redundant in th

2019-03-05 14:03发布

问题:

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

回答1:

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 using this(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.



回答2:

When in doubt, always consult the specification:

If a constructor body does not begin with an explicit constructor invocation and the constructor being declared is not part of the primordial class Object, then the constructor body implicitly begins with a superclass constructor invocation "super();", an invocation of the constructor of its direct superclass that takes no arguments.