今天测试代码时遇到
的报错,代码如下:
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"; } }
【踩坑】报错 non-static method xxx() cannot be referenced from a static context
原文:https://www.cnblogs.com/lipohong/p/10594600.html