对于我的程序,我有两个矩形构造函数。一个没有参数,一个有2个长度和宽度参数。在我的测试类中,我使用2个参数调用构造函数,但是我得到错误rectangle in class rectangle can not be applied to given types
任何人都可以告诉我为什么它只识别默认的矩形构造函数而不是带参数的构造函数。谢谢
找到矩形的类。
public class Rectangle
{
//declares instance variables
private int length;
private int width;
/**
* Rectangle
* sets the length and width to default values
* pre: none
* post: length and with set = to 1
*/
public void Rectangle()
{
// sets length and width as 1 if no parameters are entered
length = 1;
width = 1;
}
/**
* Rectangle
* sets the length and width to values entered by user
* pre: none
* post: length and width set = to user input
*/
public void Rectangle ( int len, int wid)
{
//sets the legth and width as the user variable
length = len;
width = wid;
}
测试类
//rectangle object with default numbers
Rectangle rectan1= new Rectangle();
System.out.println("Area of rectangle with no parameters: "+
rectan1.area());
//rectangle object using parameters
Rectangle rectan2= new Rectangle(2,3); //ERROR RECEIVED HERE
System.out.println("Perimeter of rectangle with parameters: "+
rectan2.perimeter());
答案 0 :(得分:3)
从构造函数中删除void关键字:
public Rectangle()
{
this(1,1); // execute second constructor;
}
public void Rectangle ( int len, int wid)
{
//sets the legth and width as the user variable
length = len;
width = wid;
}
请查看此oracle doc。正如你所看到的那样,构造函数不会返回任何东西,但是方法会返回。
答案 1 :(得分:2)
如果要创建方法,则应使用void
,如果要创建构造函数,只需删除它,如下所示:
public Rectangle()
{
...
}
和
public Rectangle ( int len, int wid)
{
...
}
快乐编码