Java inheritance - constructors

前端 未结 5 690
盖世英雄少女心
盖世英雄少女心 2021-01-02 04:22

While studying for my finals, I came across the following statement in the book from which I am currently studying. Considering the following code :

class A         


        
5条回答
  •  轮回少年
    2021-01-02 04:54

    If you have a the base class having a default constructor (no-arg constructor), when you extend B, you don't need to explicitly call super() because it is called any way.

    But when you have a constructor with arguments, when making the contructor with parameters in B, you need to pass in super() a parameter for A

    example :

    class A {
        public A(int x) {   }
      }
    
      class B extends A {
        public B(int x ) 
        {
           super(x); // need to specify the parameter for class A
           //... 
        }
      }
    

提交回复
热议问题