为什么我们不能从静态方法调用非静态方法?

huangapple 未分类评论54阅读模式
英文:

Why cant we call nonstatic method from static method?

问题

我有一个名为Program的类。这里有一个main方法。这是一个静态方法。我创建了一个简单的getAllSum方法来返回三个值的和。但是,如果我删除static关键字,我会得到错误:

  1. **无法从类型Program进行非静态方法getALlsum(int, int, int)的静态引用
  2. **

如果我从静态方法调用非静态方法,为什么非静态方法需要变成静态方法呢?

关于静态方法,我学到的是:

  1. 可以通过类名调用,而不需要使用对象。
  2. 每个对象共享相同的变量。

但是,我感到困惑的是为什么我们不能从静态函数调用非静态函数呢?背后的原因是什么?

  1. public class Program {
  2. public static void main(String[] args) {
  3. int l = getAllSum(1, 2, 3);
  4. System.out.println(l);
  5. }
  6. public static int getAllSum(int a, int b, int c) {
  7. return (a + b + c);
  8. }
  9. }
英文:

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:

  1. **Cannot make a static reference to the non-static method getALlsum(int, int, int) from the type Program
  2. **

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:

  1. Can be called from class name instead of using object.
  2. 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?

  1. public class Program {
  2. public static void main(String[] args) {
  3. int l=getALlsum(1,2,3);
  4. System.out.println(l);
  5. }
  6. public static int getAllSum(int a,int b,int c) {
  7. return (a+b+c);
  8. }
  9. }

答案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

huangapple
  • 本文由 发表于 2020年3月15日 21:24:41
  • 转载请务必保留本文链接:https://java.coder-hub.com/60693393.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定