John W
John W

Reputation: 171

why does the subclass have to invoke the no args constructor in the super class?

On the piece of code below, I understand super(t) in the subclass is explicitly invoking a no-args constructor in its superclass (class B). What I seem to be having problems understanding is why does the subclass have to invoke the no-args constructor in the superclass? I can't seem to work out the purpose of this?

public class Test {

    public static void main(String[] args) {

       B b = new B(5);

    }
}
class A extends B {
    public A(int t)  {
        super(t);
        System.out.println("A's constructor is invoked");
    }
}

class B  {



    public B(int k)   {
    System.out.println("B's constructor is invoked");
    }
}

Upvotes: 0

Views: 1523

Answers (3)

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41200

Super must be instantiated before sub like parent must exists before child.

I understand super(t) in the subclass is explicitly invoking a no-args constructor in its >superclass (class B)

super(t) actually super(5) will invoke public B(int k).
super() try to invoke public B() which does not exist.

Note: compiler provides no-arg constructor if there is no constructor available in the class.

Upvotes: 3

Henry
Henry

Reputation: 43728

Your class B does not have a no-args constructor (that would be one without arguments). If it had one, it would be called automatically by the constructors of A. But in the example you have to call it manually with super(t) in order to specify the argument(s) that should be used.

Upvotes: 1

Karthik T
Karthik T

Reputation: 31952

super(t) in the subclass is explicitly invoking a no-args constructor in its superclass (class B).

No, super(t) can be rewritten as B(t). It is invoking the constructor you have shown in the code.

I believe what you are thinking about is

If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass.

From http://docs.oracle.com/javase/tutorial/java/IandI/super.html

i.e If the code did not do super(t) the default no-args constructor would be called, However

If the super class does not have a no-argument constructor, you will get a compile-time error

Upvotes: 1

Related Questions