Header Ads

  • Breaking Now

    Does a class inherit constructors from its superclass?

    The answer is No.Constructors cannot be inherited.Constructors are used to initialize a valid sate of an object.Whenever a subclass instance is created then it calls no argument default constructor of super class.

    The following code will explain implicit call to default constructor of base class:-

    class Base {
    Base() {
    System.out.println("I am constructing Base");
    class Child extends Base {
    Child() {
    System.out.println("I am constructing Child");

    public class A {
    public static void main(String[] args) {
    Child child = new Child();

    Once executed this code will print:

    I am constructing Base
    I am constructing Child

    It means when a child class object is created it inherently calls no arg default constructor of base class.


    1. a clarification - so when do we use super(); in our constructor?

    2. This is why in a sub class's constructor, the call of super constructor must be first line. The compiler inserts the implicit super class constructor (no argument constructor) if no super constructor call is found at the beginning. If super class does not have a implicit constructor and child class constructor does not call super class constructor, compiler gives an error.


    Post Top Ad

    Post Bottom Ad