Java inheritance concept referencing superclass constructor?

I did a simple Inheritance program, but I got confused during the execution of this program.

Here is a simple program:

class Box {
    double width;
    double height;
    double depth;
    Box(double w, double h, double d) {
        width = w;
        height = h;
        depth = d;
    }
    //Error on removing the Box() Constructor
    Box() {
        width = -1; 
        height = -1;   
        depth = -1;  
    }

    double volume() {
        return width * height * depth;
    }
}

class BoxWeight extends Box {
    double weight,h,w,d; 

    BoxWeight(double w, double h, double d, double m) {

        // If i add super(w,h,d) here, then it is working, WHy?
        this.h = h;
        this.d = d;
        this.w = w;
        weight = m;
    }
}
class DemoBoxWeight {
    public static void main(String args[]) {
        //Implementation of above
    }
}

What bothers me when I delete the constructor Box(), it gives me an error in the line where the constructor is defined BoxWeight(double w, double h, double d, double m).The error is: "constructor Box in class Box cannot be applied to given types".

If I call super()from BoxWeight(), then it works fine. I do not understand why? I know that the concept is pretty simple, but it's hard for me to understand. Any help appreciated.

+4
source share
4 answers

The constructor BoxWeight(double w, double h, double d, double m)does not explicitly call the super constructor. This means that the default constructor is called Box().

BoxWeight, .

, :

BoxWeight(double w, double h, double d, double m) {

        super(w,h,d);
        this.h = h;
        this.d = d;
        this.w = w;
        weight = m;
}

.

+5

, , ( ).

, super(w, h, d). Box. super() . super() - . , .

, , Box. , super()

+2

, .

, , , .

- , super(). , , ( ) .

, , , BoxWeight super(), super() . , Box Box().

Box(), Box BoxWeight. , , , . , Box, , .

, : " " . , . : " Box Box ".

+2

What actually happens in your program when you delete the default constructor Box, then the compiler does not have a constructor to call from the constructor BoxWeight. This creates confusion for the compiler and therefore gives you an error.

But, however, when you send a call to a constructor Boxthat takes parameters, your code compiles without any errors.

+1
source

Source: https://habr.com/ru/post/1618707/


All Articles