Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there a problem with a non-static variable being read from main?

Tags:

java

static

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

like image 602
Sam Avatar asked Jan 12 '11 03:01

Sam


People also ask

Why non-static variable cannot be referenced from a static method?

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.

What is the problem with static variables?

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

Should static variables be read only data?

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.

What is non static variable in C++?

// 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.


1 Answers

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.

like image 85
templatetypedef Avatar answered Oct 06 '22 01:10

templatetypedef