我有一个课程Program。这里有主要方法,它是静态方法。我创建了一个简单的 getAllSum 方法可返回三个值的和。但是,如果我删除static关键字,则会收到错误消息:
**Cannot make a static reference to the non-static method getALlsum(int, int, int) from the type Program
**
如果我要从静态方法调用函数到非静态方法,那么为什么必须要使非静态方法成为静态方法?
我了解到的静态方法是:
但是,让我感到困惑的是,为什么我们不能从静态函数中调用非静态函数?其背后的原因是什么?
public class Program {
public static void main(String[] args) {
int l=getALlsum(1,2,3);
System.out.println(l);
}
public static int getAllSum(int a,int b,int c) {
return (a+b+c);
}
}
答案 0 :(得分:-1)
您不能调用非静态方法或从main或任何其他静态方法访问非静态字段,因为非静态成员属于类实例,而不是整个类。
您需要创建您的类的实例,然后调用您的方法