[Two Solutions] non-static method xxx() cannot be referenced from a static context

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: