英文:
Why cant we call nonstatic method from static method?
问题
我有一个名为Program的类。这里有一个main方法。这是一个静态方法。我创建了一个简单的getAllSum方法来返回三个值的和。但是,如果我删除static关键字,我会得到错误:
**无法从类型Program进行非静态方法getALlsum(int, int, int)的静态引用
**
如果我从静态方法调用非静态方法,为什么非静态方法需要变成静态方法呢?
关于静态方法,我学到的是:
- 可以通过类名调用,而不需要使用对象。
- 每个对象共享相同的变量。
但是,我感到困惑的是为什么我们不能从静态函数调用非静态函数呢?背后的原因是什么?
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);
}
}
英文:
I have a class Program. Here it has main method.It is static method. I created a simple
getAllSum method to return sum of three values.But, if i remove static keyword then i get error as:
**Cannot make a static reference to the non-static method getALlsum(int, int, int) from the type Program
**
If I am calling a function from static method to non static method then,why it is necessary to become non static method to be static?
Static method I have learned about them is that:
- Can be called from class name instead of using object.
- Each object shares the same variable.
But,I am getting confuse why cant we call a nonstatic function from static function?What is the reason behind this?
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);
}
}
答案1
得分: -1
你不能从主函数或任何其他静态方法调用非静态方法,或者访问非静态字段,因为非静态成员属于类实例,而不属于整个类。
你需要创建一个类的实例,并调用你的方法。
英文:
You cannot call non-static methods or access non-static fields from main or any other static method, because non-static members belong to a class instance, not to the entire class.
You need to make an instance of your class, and call your method
专注分享java语言的经验与见解,让所有开发者获益!
评论