【踩坑】報錯 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"; } }
相關文章
相關標籤/搜索