【问题标题】:Can someone please explain to me like I'm 5 years old the error " static reference to the non-static method " [closed]有人可以像我 5 岁那样向我解释错误“对非静态方法的静态引用”[关闭]
【发布时间】:2013-11-10 23:36:59
【问题描述】:

这个错误困扰着我:

cannot make a static reference to the non-static method XYZ from the type ABC

我的眼睛只是呆滞。我意识到以前有人问过这个问题,但我想要 5 岁的治疗。只是没有意义..

我正在运行一个类,我在 public static void main 中有代码,然后我在它之外创建了一个函数。

【问题讨论】:

  • 一个 5 岁的孩子会理解你 cannot make a static reference to the non-static method XYZ from the type ABC 并相应地更改他们的代码。查看实例是什么。
  • @SotiriosDelimanolis - 好的,谢谢
  • 如果您解释一下现有解释的哪些部分不清楚,这将有所帮助
  • @RichardTingle - 是的,我知道。好的,谢谢
  • 您的代码至少需要一个new 才能工作。

标签: java static-methods


【解决方案1】:

您尝试在 main 中调用的函数没有 static 关键字。添加它,编译器不会抱怨。

public class Foo {
    public static void main(String [] args) {
        bar();
    }

    public static void bar() {
        System.out.println("compiler won't complain");
    }
}

这并不意味着这样做是正确的。

静态方法和成员与相关联;非静态方法和成员与实例相关联。确保您了解其中的区别。如果不这样做,就很难进行面向对象的编码。

如果它是非静态方法,您需要执行以下操作:

public class Foo {
    public static void main(String [] args) {
        Foo foo = new Foo();
        foo.bar();  // Associated with the new Foo instance named foo.
    }

    public void bar() {
        System.out.println("compiler won't complain");
    }
}

【讨论】:

  • 如果答案正确,请接受。
  • 你说得对,它会再次发生。 Duffymo 向您展示了一个解决方案,它实际上只是学习 java 时的创可贴。很快您将不得不退出 main 并使用非静态方法。
  • 会做的,非常感谢
  • 这是现在点击,类和实例的概念。非常感谢楼主
【解决方案2】:

归结为类成员和实例成员。请阅读此文档以了解有关为什么类成员不能直接引用实例成员的更多详细信息。

http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

【讨论】:

  • 而且,我知道大多数 5 岁的孩子都喜欢骑自行车 :)
  • 这是更多评论,但还可以
【解决方案3】:

Java 有“静态”和“实例”方法。 “静态”方法在其定义中包含 static(例如,对于您的 main 方法,您总是说 static。“实例”方法的定义中没有 static 一词。

可以从任何环境调用静态方法,使用ClassName.staticMethodName(parms)。实例方法只能使用对该方法类的对象的引用来调用。即,您必须使用objectReference.instanceMethodName(parms),其中objectReference 引用方法类的对象。 (如果从类的另一个实例方法内部调用,则隐含 objectReference。)

【讨论】:

    【解决方案4】:

    如果您在main 函数旁边创建的函数不是静态的,那么您不能从静态的main 方法调用它。 那是因为您没有创建包含这两个函数的类的任何实例。非静态方法(因此,实例方法)本质上需要该类的实例才能被调用。

    假设您有以下示例:

    public class Test{
        public static void main(String args[]){
        }
    
        public void doSomething(){
        }
    }
    

    如果你想从main 方法调用doSomething() 方法,它必须看起来像

    public static void main(String args[]){
        new Test().doSomething();
    }
    

    【讨论】:

      猜你喜欢
      • 2014-03-16
      • 2021-04-17
      • 1970-01-01
      • 2013-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-10
      • 1970-01-01
      相关资源
      最近更新 更多