【发布时间】:2014-04-29 00:07:07
【问题描述】:
下面是我的类文件 Rectangle 和带有 main 方法的类文件 testRectangle。现在在 testRectangle 中,当我在“Rectangle”类中调用“perimeter”方法时,我收到一条错误消息。我收到的错误消息指出,“将 'perimeter()' 的修饰符更改为 'static'。该方法不能是静态的,因为我将在主方法中有几个不同的矩形对象。我做错了吗?任何帮助都会不胜感激。
矩形.java
public class Rectangle {
private int length;
private int width;
Rectangle(int len, int wid) {
length = len;
width = wid;
}
public int perimeter(Rectangle rec){
int p = 2*length + 2* width;
return p;
}
}
testRectangle.java
public class testRectangle {
public static void main(String[] args) {
Rectangle r1 = new Rectangle(5,4);
int r1Perimeter = Rectangle.perimeter(r1);
//the line above this is where I get the error message
//the red squiggly line goes under "Rectangle.perimeter(r1);
}
}
【问题讨论】:
-
当它只是一个实例方法时,您将它称为类方法。而不是
Rectangle.perimeter应该是r1.perimeter