【问题标题】:Cannot make a static reference to the non-static method fxn(int) from the type Two [duplicate]无法从类型二中对非静态方法 fxn(int) 进行静态引用 [重复]
【发布时间】:2012-07-14 13:25:33
【问题描述】:

可能重复:
What is the reason behind “non-static method cannot be referenced from a static context”?
Cannot make a static reference to the non-static method
cannot make a static reference to the non-static field

我无法理解我的代码有什么问题。

class Two {
    public static void main(String[] args) {
        int x = 0;

        System.out.println("x = " + x);
        x = fxn(x);
        System.out.println("x = " + x);
    }

    int fxn(int y) {
        y = 5;
        return y;
    }
}

线程“main”java.lang.Error 中的异常:未解决的编译问题: 无法从类型 Two 对非静态方法 fxn(int) 进行静态引用

【问题讨论】:

  • 不是你的反对者,但你会想通过the Java tutorials 或一本基本的教科书来学习 Java 的基础知识。
  • 如果您不了解我现在的情况,请不要对这个问题投反对票。 :/ 我还在 Head First Java 的第 4 章,对关于 return 的声明感到困惑。我只是想这样做。
  • 在提出问题之前,您应该已经搜索了 SO 以获得答案。
  • @Stephen - 我搜索过。但它没有回答我的问题
  • @Kunal - 我有所不同。第二个“可能重复”与您的标题字符串非常匹配,并直接回答您的问题。如果你没有找到它,你看起来不正确。如果您确实找到了它,那么您没有正确阅读它。

标签: java


【解决方案1】:

由于main 方法是staticfxn() 方法不是,所以您必须先创建Two 对象才能调用该方法。因此,要么将方法更改为:

public static int fxn(int y) {
    y = 5;
    return y;
}

或将main中的代码改成:

Two two = new Two();
x = two.fxn(x);

Java Tutorials 中阅读更多关于static 的信息。

【讨论】:

    【解决方案2】:

    您无法访问 fxn 方法,因为它不是静态的。静态方法只能直接访问其他静态方法。如果你想在你的 main 方法中使用 fxn,你需要:

    ...
    Two two = new Two();
    x = two.fxn(x)
    ...
    

    也就是说,创建一个 Two-Object 并调用该对象的方法。

    ...或将 fxn 方法设为静态。

    【讨论】:

      【解决方案3】:

      您不能从静态方法中引用非静态成员。

      非静态成员(如您的 fxn(int y))只能从您的类的实例中调用。

      例子:

      你可以这样做:

             public class A
             {
                 public   int fxn(int y) {
                    y = 5;
                    return y;
                }
             }
      
      
        class Two {
      public static void main(String[] args) {
          int x = 0;
          A a = new A();
          System.out.println("x = " + x);
          x = a.fxn(x);
          System.out.println("x = " + x);
      }
      

      或者你可以将你的方法声明为静态的。

      【讨论】:

        【解决方案4】:
        1. 静态方法不能访问非静态方法或变量。

        2. public static void main(String[] args) 是静态方法,因此不能访问非静态public static int fxn(int y) 方法。

        3. 试试这个方法……

          静态 int fxn(int y)

          public class Two {
          
          
              public static void main(String[] args) {
                  int x = 0;
          
                  System.out.println("x = " + x);
                  x = fxn(x);
                  System.out.println("x = " + x);
              }
          
              static int fxn(int y) {
                  y = 5;
                  return y;
              }
          

          }

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-07-20
          • 2019-06-29
          • 1970-01-01
          • 2014-06-08
          • 2013-01-15
          • 2015-08-18
          相关资源
          最近更新 更多