Java中与构造函数相关的错误
我是Java新手,写了这段代码。它有一个简单的类框和两个属性width和length以及一些函数Java中与构造函数相关的错误,java,constructor,default-constructor,Java,Constructor,Default Constructor,我是Java新手,写了这段代码。它有一个简单的类框和两个属性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
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()
{
length=0;
width=0;
}
在Java中,如果没有创建任何构造函数,那么编译器将创建默认构造函数本身。但是,如果您已经创建了参数化构造函数,并且试图使用默认构造函数而没有定义它,那么编译器将产生您得到的错误。为
Box
定义的唯一构造函数是Box(int w,int l)
将main()
更改为:
Box mybox = new Box(5, 5);
mybox.showBox();
或者更改
框
使构造函数不带参数,并初始化宽度
和长度
,或者只使用定义的构造函数并将长度和宽度传递给它
Box myBox = new Box(4,3);
myBox.showBox();
然后,您定义的构造函数使用传递的int值调用方法setLength()和setWidth()。(在本例中,值为4和3)定义自定义构造函数时,默认构造函数将不再可用: 如果您想使用它,您应该显式地定义它 您可以定义两个构造函数,以使以下各项正常工作
Box(int w, int l)
{
setLength(l);
setWidth(w);
}
Box()
{
//this is the default
}
现在,您可以同时使用这两种方法:
new Box()
new Box(w,l)
在构造函数中将
length
和width
设置为0有点多余,因为它们将被初始化为这些值。这是正确的。但我认为最好还是写出来,因为他是Java新手。。所以请有人解释一下……除非你特别想让构造函数不公开,否则就让它们公开。即使你不是,在我看来,最好明确地说出他们的范围,让人们知道这不是一个意外。