gpt4 book ai didi

java - 扩展类时构造函数出错

转载 作者:行者123 更新时间:2023-12-02 02:15:59 25 4
gpt4 key购买 nike

我是java初学者,在编码过程中,我遇到了一个对我来说不容易理解的问题。我的问题是“编写一个类,其中包含一种方法来查找矩形的面积。创建一个子类来查找矩形盒子的体积。”我面临的错误如下。我为此编写了这段代码:-

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

最佳答案

当您创建子对象时,首先父构造函数起作用。在此示例中,当您创建 矩形框 对象时,首先矩形构造函数工作,然后矩形框构造函数工作。因此,您的子构造函数必须调用父构造函数。

通常,如果父类和子类都有默认构造函数,则子类默认构造函数会调用父类默认构造函数。但是您没有默认构造函数,因为此 RectangleBox 构造函数必须调用 Rectangle 构造函数。要调用父构造函数,您必须使用 super 关键字。然后你的代码:

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

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

}

关于java - 扩展类时构造函数出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49299795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com