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";
}
}
Reason:
Class variables and class methods cannot be called directly
Solution 1:
Change the method to a class method as follows:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Greeting: " + GoodByeWorld.sayGoodbye());
}
}
class GoodByeWorld {
public String static sayGoodbye() {
return "GoodBye";
}
}
Solution 2:
Generate an instance and call the non static methods in the instance, as follows:
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";
}
}
Similar Posts:
- Java error: No enclosing instance of type E is accessible. Must qualify the allocation with an enclosing
- [Problems with the use of internal classes] No enclosing instance of type Outer is accessible. Must qualify the allocation with an enclo
- [Solved] Java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Double
- [Solved] Java Call Error: java.lang.IllegalArgumentException: wrong number of arguments
- 【Java】No enclosing instance of type XXX is accessible. Must qualify the allocation with an enclos…
- Convert Object to List>, avoiding Unchecked cast: ‘java.lang.Object’ to ‘java.util.List
- Solution to the problem of Java program “resource leak: ‘SC’ is never closed” in vscode
- Eclipse Error:The selection cannot be launched, and there are no recent launches
- Java Thread wait, notify and notifyAll Example
- Java – Convert bytes to unsigned bytes