Does a subclass NEED to have a constructor?

zaynv picture zaynv · Mar 18, 2014 · Viewed 14.4k times · Source

I've been learning about inheritance and I was just curious. I know that the subclass will automatically call the superclass's constructor even if you don't use the super() operator, so I wanted to know if it is even necessary for a subclass to have a constructor in it.

Answer

Ted Hopp picture Ted Hopp · Mar 18, 2014

A subclass needs a constructor if the superclass does not have a default constructor (or has one that is not accessible to the subclass). If the subclass has no constructor at all, the compiler will automatically create a public constructor that simply calls through to the default constructor of the superclass.

Regarding calling super(): the first thing every constructor must do is either call a different constructor in the same class by calling this() (possibly with some arguments) or call a constructor of its superclass by calling super() (again, possibly with arguments). Neither of those calls can go anywhere else. If a constructor doesn't start with either one, the compiler will automatically insert a call to super() (without any arguments). So if the behavior you want is to call through to the default superclass constructor (and, many times, it is) then you don't need to explicitly call super() yourself.

There's also one situation where you do not need to provide a constructor (in fact, you can't provide one) even when the superclass has no default constructor. This case (described in section 15.9.5.1 of the Java Language Sepcification) is when you create an anonymous subclass of a class using a non-default constructor; the compiler will automatically create a constructor with the correct arguments and call up to the corresponding (non-default) superclass constructor. For instance:

class X {
    public X(int value) { ... } // no default constructor!
    public void foo() { ... }
}

X myX = new X(3) {
    @Override
    public void foo() { ... }
};

Then myX will be an instance of an anonymous subclass of X with a compiler-generated constructor that takes an int argument and calls super(intArg).

Because you cannot write a constructor for anonymous classes, there's an issue: what if you need to do some object initialization when the object is created? The solution is to use an instance initializer block. For example:

X myX = new X(3) {
    // Field unique to this subclass of X:
    private int baz;
    {
        // code here runs as if it were at the start of every constructor
        baz = ...;
    }
    @Override
    public void foo() { ... }
};