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(); }
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With