"Non-Static Method Cannot Be Referenced from a Static Context" Error

What is the reason behind non-static method cannot be referenced from a static context?

You can't call something that doesn't exist. Since you haven't created an object, the non-static method doesn't exist yet. A static method (by definition) always exists.

non-static method cannot be referenced from a **static context**. What is static content here?

Your main-method is the static context, and you are trying to call the non-static method display() from it. That doesn't work even if it is in the same class. To have the disply method non-static you have to do this.

public static void main(String[] args) throws FileNotFoundException{
ReverseLL r = new ReverseLL();
r.display(head);

}

public void display(Node head){
...
}

Non-Static method cannot be referenced from a static context with methods and variables

You need to make both your method - printMenu() and getUserChoice() static, as you are directly invoking them from your static main method, without creating an instance of the class, those methods are defined in. And you cannot invoke a non-static method without any reference to an instance of the class they are defined in.

Alternatively you can change the method invocation part to:

BookStoreApp2 bookStoreApp = new BookStoreApp2();
bookStoreApp.printMenu();
bookStoreApp.getUserChoice();

Method reference - non-static method cannot be referenced from a static context

Assuming the caller class has an instance of ClassA and you want to specify which methods to call, you'll need to use a Function that accepts the instance and returns the result of the method call. In other words, you'll need to change the return type to List<Function<ClassA, String>>. The method body can remain the same. To invoke the functions, you'll need to call apply(), e.g.:

ClassA instance = ...
for (Function<ClassA, String> method : getData()) {
String result = method.apply(instance);
System.out.println(result);
}

Alternatively, as pointed out by @Thilo, you can have the method accept an instance and return a list of suppliers that invoke a method on the provided instance:

public List<Supplier<String>> getData(ClassA instance) {
return Arrays.asList(
instance::getOne,
instance::getTwo
);
}


Related Topics



Leave a reply



Submit