【踩坑】报错 non-static method xxx() cannot be referenced from a static context
今天测试代码时遇到
- 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"; } }
原因:
不能直接调用类变量和类方法。
解决方法一:
将方法改成类方法,如下:
public class HelloWorld { public static void main(String[] args) { System.out.println("Greeting: " + GoodByeWorld.sayGoodbye()); } } class GoodByeWorld { public String static sayGoodbye() { return "GoodBye"; } }
解决方法二:
生成实例,调用实例中的非静态方法,如下:
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"; } }