Java Inheritance error: Implicit Super Constructor is undefined

前端 未结 2 554
情深已故
情深已故 2020-12-10 09:33

I am a novice to Java and just learning OOP concepts. Please review my code. I am getting the following error.- Implicit Super Constructor is undefined.

相关标签:
2条回答
  • 2020-12-10 09:44

    A constructor always calls the super constructor, always. If no explicit call to the super constructor is made, then the compiler tries to set it up so that it will call the default parameter-less constructor. If a default parameter-less constructor doesn't exist, a compilation error as you're seeing is shown and compilation will fail.

    The solution in your case is to explicitly call the appropriate super constructor as the first line of your Box's constructor, and this makes perfect sense too if you think about it since you want to initialize the super with a, b, and c just as written in its constructor:

    class BoxSub extends BoxSuper
    {
        int weight;
        BoxSub(int a,int b,int c,int d)
        {
            super(a, b, c);
            // height=a;
            // length=b;
            // width=c;
            weight=d;
        }
    }
    
    0 讨论(0)
  • 2020-12-10 09:51

    You are receiving this error because BoxSuper does not have a no-arg constructor. During your constructor call in BoxSub, if you do not define the super constructor call Java tries to automatically call the no-arg super() constructor.

    Either define a super constructor call in BoxSuper like so:

    class BoxSub extends BoxSuper
    {
        int weight;
        BoxSub(int a,int b,int c,int d)
        {
            super(a, b, c);
            weight=d;
        }
    }
    

    or define a no-arg constructor in BoxSuper:

    class BoxSuper
    {
        int height;
        int length;
        int width;
    
        BoxSuper(){}
    ...
    
    0 讨论(0)
提交回复
热议问题