我是 Java 新手,编写了这段代码。它有一个简单的类 Box 和两个属性 width 和 length 以及一些函数。
class Box
{
private int width;
private int length;
Box(int w, int l)
{
setWidth(w);
setLength(l);
}
public void setWidth(int width)
{
this.width = width;
}
public int getWidth()
{
return width;
}
public void setLength(int length)
{
this.length = length;
}
public int getLength()
{
return length;
}
void showBox()
{
System.out.print("Box has width:"+width +" length:"+length);
}
}
class Main {
public static void main(String[] args)
{
Box mybox = new Box();
mybox.setLength(5);
mybox.setWidth(5);
mybox.showBox();
}
}
我收到此错误。我该如何修复它?有人可以解释一下吗?
Box.java:30: cannot find symbol
symbol : constructor Box()
location: class Box
Box mybox=new Box();
最佳答案
为 Box
定义的唯一构造函数是 Box(int w, int l)
。
将 main()
更改为:
Box mybox = new Box(5, 5);
mybox.showBox();
或者更改 Box
使其具有不带参数并初始化 width
和 length
的构造函数。
关于java - Java 中与构造函数相关的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9275466/