Tonmoay Deb Tonmoay Deb - 1 month ago 11
Java Question

Why child class in Java always tries to make parent constructor call

Suppose, I have created 1 child class and one parent class. One main class for loading program.

B extends A. Program is like:

class A {

public A(String name) {

}

}

class B extends A {

}


class load {

public static void main(String[] args) {
B launch = new B();
}
}


The above code gives us an error. Because we didn't call the super class with the specific String parameter from the child class.

But we are calling child class. Why does it try to call parent class? It(child class constructor) also doesn't send any parameter to a parent class constructor. May I get the answer of this strange occurrence, please?

Answer

When you don't supply a constructor, you have a default of essentially:

public class B extends A {

    public B() {
        super();
    }

}

What doesn't work here, however, is that A has no zero-args constructor, so the super call is invalid.

You need to supply a constructor manually which supplies one:

public class B extends A {

    public B() {
        super("foo");
    }

    //or
    public B(String name) {
        super(name);
    }

}

This is due to the fact a child class is a parent class, so a parent's fields and constructors are initialized/called before any members of the child class are.

Comments