【踩坑】报错 non-static method xxx() cannot be referenced from a static context

今天测试代码时遇到java

  • Error:(6, 55) java: non-static method sayGoodbye() cannot be referenced from a static context

的报错,代码以下:测试

public class HelloWorld { public static void main(String[] args) { System.out.println("Greeting: " + GoodByeWorld.sayGoodbye()); } } class GoodByeWorld { public String sayGoodbye() { return "GoodBye"; } }

缘由:

不能直接调用类变量和类方法。spa

解决方法一:

将方法改为类方法,以下:code

public class HelloWorld { public static void main(String[] args) { System.out.println("Greeting: " + GoodByeWorld.sayGoodbye()); } } class GoodByeWorld { public String static sayGoodbye() { return "GoodBye"; } }

解决方法二:

生成实例,调用实例中的非静态方法,以下:blog

public class HelloWorld { public static void main(String[] args) { GoodByeWorld greeting = new GoodByeWorld(); System.out.println("Greeting: " + greeting.sayGoodbye()); } } class GoodByeWorld { public String sayGoodbye() { return "GoodBye"; } }
相关文章
相关标签/搜索