public class Test {
public static void main (String [] args ){
int a = calcArea(7, 12);
System.out.println(a);
}
int calcArea(int height, int width) {
return height * width;
}
}
出现以下错误:
非静态方法calcArea(int,int)无法从静态内容引用
这是什么意思?我该如何解决这个问题..?
编辑:
根据您的建议,我创建了一个实例,即new test():
public class Test {
int num;
public static void main (String [] args ){
Test a = new Test();
a.num = a.calcArea(7, 12);
System.out.println(a.num);
}
int calcArea(int height, int width) {
return height * width;
}
}
这样做正确吗?如果我这样做有什么不同...
public class Test {
public static void main (String [] args ){
int a = calcArea(7, 12);
System.out.println(a);
}
static int calcArea(int height, int width) {
return height * width;
}
}
calcArea
是一个实例方法, 它在对象上被调用, 并(通常)执行与该对象相关的操作. 而第二个方法将calcArea
设置为一个静态 (类) 方法, 通常只是执行不需要任何对象实例的操作。在这里,calcArea
在其参数上工作并返回结果,这使它成为一个好的类方法。现在,在一个名为 Rectangle 的类中,有一个名为calcArea()
的实例方法 (没有参数),您可以看到它可能会将自己的高度和宽度成员变量相乘以返回一个对象特定的结果。 - Sdaz MacSkibbons