Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

static

The very common beginner mistake is when you try to use a class property "statically" without making an instance of that class. It leaves you with the mentioned error message:

You can either make the non static method static or make an instance of that class to use its properties.

What the reason behind this? Am not concern with the solution, rather the reason.

private java.util.List<String> someMethod(){     /* Some Code */     return someList;             }  public static void main(String[] strArgs){                // The following statement causes the error.      java.util.List<String> someList = someMethod();          } 
like image 222
Sajal Dutta Avatar asked Nov 14 '08 17:11

Sajal Dutta


People also ask

How do you fix non static method Cannot be referenced from a static context?

There is one simple way of solving the non-static variable cannot be referenced from a static context error. In the above code, we have to address the non-static variable with the object name. In a simple way, we have to create an object of the class to refer to a non-static variable from a static context.

Why static method Cannot access non static methods?

Namely, static methods can only use static variables and call static methods—they cannot access instance variables or methods directly, without an object reference. This is because instance variables and methods are always tied to a specific instance, i.e., object of their class.

Why static method Cannot call non static method in Java?

You cannot call non-static methods or access non-static fields from main or any other static method, because non-static members belong to a class instance, not to the entire class.


2 Answers

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.

like image 65
Brian Knoblauch Avatar answered Oct 18 '22 19:10

Brian Knoblauch


The method you are trying to call is an instance-level method; you do not have an instance.

static methods belong to the class, non-static methods belong to instances of the class.

like image 37
Steven A. Lowe Avatar answered Oct 18 '22 20:10

Steven A. Lowe