Search code examples
javaconstructorargumentsextendextends

Error on constructor while extending class


I am a beginner in java and during coding, i faced an issue which is not easy to understand for me. My question is "Write a class with a method to find the area of a rectangle. Create a subclass to find the volume of a rectangular shaped box." The error i am facing is below. I wrote this code for the same:-

class Rectangle
{
    public int w;
    public int h;

    public Rectangle(int width, int height)
    {
        w=width;
        h=height;
    }
    public void area()
    {
        int area=w*h;
        System.out.println("Area of Rectangle : "+area);
    }
}
class RectangleBox extends Rectangle
{
    int d;
    public RectangleBox(int width, int height, int depth)
    {
        d=depth;
        w=width;
        h=height;   

    }
    public void volume()
    {
        int volume=w*h*d;
        System.out.println("Volume of Rectangle : "+volume);
    }
}
class programm8
{
    public static void main(String args[])
    {
    Rectangle r = new Rectangle(10,20);
    RectangleBox rb = new RectangleBox(4,5,6);
    r.area();
    rb.volume();
    }
}

Error:(23, 5) java: constructor Rectangle in class code.Rectangle cannot be applied to given types; required: int,int found: no arguments reason: actual and formal argument lists differ in length


Solution

  • When you create a child object firstly a parent constructor works. In this example when you create a RectangleBox object, firstly Rectangle constructor works after that RectangleBox constructor works. So, your child constructor have to call a parent constructor.

    Normally if you have default constructors for parent and child classes, child default constructor calls parent default constructor. But you dont have default constructors because of this RectangleBox constructor have to call a Rectangle constructor. And for calling a parent contructor you have to use super keyword. And then your code:

    public Rectangle(int width, int height)
        {
            w=width;
            h=height;
        }
    
    public RectangleBox(int width, int height, int depth)
        {
            super(width, width)
            h=height;   
    
        }