我无法编译以下代码:
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) 不能从静态内容中引用
这是什么意思?我怎样才能解决这个问题..?
EDIT:
根据您的建议,我创建了一个新的 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;
}
}
您的 main 是静态的,因此您可以在没有类 test 实例的情况下调用它(new test()
)。但它调用calcArea
这不是静态的:它需要类的实例
我想你可以这样重写:
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;
}
}
正如评论所暗示的那样,其他答案也表明了,你可能不想走这条路:你只会得到静态函数。弄清楚代码中的静态实际上应该是什么,也许让自己成为一个对象并从那里调用函数:D
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)