String name = "Marcus";
static String s_name = "Peter";
public static void main(String[] args) {
System.out.println(name);//ERROR
System.out.println(s_name);//OK
}
ERROR: Cannot make a static reference to the non-static field name
In this article, let’s discuss why non-static variable cannot be referenced from a static method. Static Method: A static method is a method that belongs to a class, but it does not belong to an instance of that class and this method can be called without the instance or object of that class.
There are 2 main problems with static variables: Thread Safety - static resources are by definition not thread-safe Code Implicity - You do not know when a static variables is instantiated and whether or not it will be instantiated before another static variable
From my point of view static variable should be only read only data or variables created by convention. For example we have a ui of some project, and we have a list of countries, languages, user roles, etc.
// a non static variable. Non static variable accessed using instance of a class. Non Static variable 10 Non static variables can be accessed using instance of a class Non static variables cannot be accessed inside a static method. Static variables reduce the amount of memory used by a program.
The reason this causes a problem is that main
is a static method, which means that it has no receiver object. In other words, it doesn't operate relative to some object. Consequently, if you try looking up a non-static field, then Java gets confused about which object that field lives in. Normally, it would assume the field is in the object from which the method is being invoked, but because main
is static this object doesn't exist.
As a general rule, you cannot access regular instance variables from static methods.
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