【踩坑】報錯 non-static method xxx() cannot be referenced from a static context
阿新 • • 發佈:2019-03-25
bye not ont ODB 原因 con cannot ood ren
今天測試代碼時遇到
- 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 { publicString 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"; } }
【踩坑】報錯 non-static method xxx() cannot be referenced from a static context