Call parent constructor

suggest change

Say you have a Parent class and a Child class. Constructing a Child always runs some Parent constructor at the very beginning of the Child constructor. Select that constructor by calling super(...) with the right arguments as the first statement. That reuses the parent constructor instead of copying it. super(...) is a constructor call, not a method call.

Without an explicit super(...) call:

The no-argument super() is called implicitly.

class Parent {
    private String name;
    private int age;

    public Parent() {} // necessary because Child calls super() with no arguments

    public Parent(String tName, int tAge) {
        name = tName;
        age = tAge;
    }
}

// This does not compile: name and age are private,
// so they are invisible to the child class.
class Child extends Parent {
    public Child() {
        // compiler implicitly calls super() here
        name = "John";
        age = 42;
    }
}

With an explicit super(...) call:

class Parent {
    private String name;
    private int age;

    public Parent(String tName, int tAge) {
        name = tName;
        age = tAge;
    }
}

class Child extends Parent {
    public Child() {
        super("John", 42);
    }
}

Note: Calls to another constructor (chaining) or the super constructor MUST be the first statement inside the constructor.

If you call the super(...) constructor explicitly, a matching parent constructor must exist (that’s straightforward, isn’t it?).

If you don’t call any super(...) constructor explicitly, your parent class must have a no-args constructor - and this can be either written explicitly or created as a default by the compiler if the parent class doesn’t provide any constructor.

class Parent{
    public Parent(String tName, int tAge) {}
}

class Child extends Parent{
    public Child(){}
}

The class Parent has no default constructor, so, the compiler can’t add super in the Child constructor. This code will not compile. You must change the constructors to fit both sides, or write your own super call, like that:

class Child extends Parent{
    public Child(){
          super("",0);
    }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents