我无法编译以下代码:
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;
}
}
出现如下错误:
Non-static method calcArea(int, int) cannot be referenced from static content
这是什么意思?我该如何解决这个问题……?
编辑:
根据您的建议,我创建了一个新的 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 是静态的,因此您可以在没有类测试实例的情况下调用它 (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
关于java - 不能从静态内容中引用非静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4774376/