Subclass constructors - Why must the default constructor exist for subclass constructors?

后端 未结 3 522
青春惊慌失措
青春惊慌失措 2020-12-18 09:05

Given a random class:

public class A {
    public T t;

    public A () {}  // <-- why is this constructor necessary for B?
    public A (T t) {
         


        
3条回答
  •  忘掉有多难
    2020-12-18 09:43

    The important point is to understand that the first line of any constructor is to call the super constructor. The compiler makes your code shorter by inserting super() under the covers, if you do not invoke a super constructor yourself.

    Also if you do not have any constructors an empty default constructor - here A() or B() - would automatically be inserted.

    You have a situation where you do not have a super(...) in your B-constructor, so the compiler inserts the super() call itself, but you do have an A-constructor with arguments so the the default A()-constructor is not inserted, and you have to provide the A()-constructor manually, or invoke the A(i)-constructor instead. In this case, I would suggest just having

    public class B extends A {
        public B (Integer i) {
            super(i);
        }
    }
    

提交回复
热议问题