I am new to Java and wrote this code. It has a simple class Box and two attributes width and length and some functions.
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();
}
}
I am getting this error. How can i fix it? Can someone please explain this.
Box.java:30: cannot find symbol
symbol : constructor Box()
location: class Box
Box mybox=new Box();
You need to define the default constructor.
Box()
{
length=0;
width=0;
}
It so happens in Java that if you have not created any constructor then the compiler will create the default constructor itself. But if you have created the parameterized constructor and are trying to use default constructor without defining it then compiler will produce the error which you got.