简体   繁体   中英

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");
    }
}

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.

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

ie 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM