Over a million developers have joined DZone.

Constructors of Sub and Super Classes in Java?

DZone 's Guide to

Constructors of Sub and Super Classes in Java?

· Java Zone ·
Free Resource

This post summarizes some commonly asked questions from Stackoverflow.com.

1. Why creating an object of the sub class invokes also the constructor of the super class?

class Super {
    String s;
    public Super(){
public class Sub extends Super {
    public Sub(){
    public static void main(String[] args){
    	Sub s = new Sub();

It prints:


When inheriting from another class, super() has to be called first in the constructor. If not, the compiler will insert that call. This is why super constructor is also invoked in the code above.

This doesn’t create two objects, only one Sub object. The reason to have super constructor called is that if super class could have private fields which need to be initialized by its constructor.

After compiler inserts the super constructor, the sub class constructor looks like the following:

public Sub(){

2. A Common Error Message: Implicit super constructor is undefined for default constructor

This is a compilation error message seen by a lot of Java developers. “Implicit super constructor is undefined for default constructor. Must define an explicit constructor”

Implicit super constructor is undefined for default constructor

This compilation error is caused because the super constructor is undefined. In Java, if a class does not define a constructor, compiler will insert a default one for the class, which is argument-less. If a constructor is defined, e.g. Super(String s), compiler will not insert the default argument-less one. This is the situation for the Super class above.

Since compiler tries to insert super() to the 2 constructors in the Sub class, but the Super’s default constructor is not defined, compiler reports the error message.

To fix this problem, simply add the following Super() constructor to the Super class, OR remove the self-defined Super constructor.

public Super(){

3. Explicitly call super constructor in sub constructor

The following code is OK:


The Sub constructor explicitly call the super constructor with parameter. The super constructor is defined, and good to invoke.

4. The Rule

In brief, the rules is: sub class constructor has to invoke super class instructor, either explicitly by programmer or implicitly by compiler. For either way, the invoked super constructor has to be defined.

5. The Interesting Question

Why Java doesn’t provide default constructor, if class has a constructor with parameter(s)?

Some answers: http://stackoverflow.com/q/16046200/127859



Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}