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

2022-11-03,,,,

今天测试代码时遇到

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";
}
}

踩坑】报错 non-static method xxx() cannot be referenced from a static context的相关教程结束。

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

下载本文的Word格式文档,以方便收藏与打印。