I was just wondering if there is a reason why an object cannot be performed with a non-static variable? I am able to fix the error, (obviously) but I was just wondering why.
-
Your first sentence doesn't make much sense actually. But the title does. Simply put: non-static variables are unique for each object and needs an instance, there is only one instance of a static (class) variable, no matter how many instances there are. And I think you're being downvoted because of your lack of research effort. There's plenty to read on this subject. – keyser Mar 10 '14 at 19:16
-
Take a look at Aaron Digulla's answer to this question. http://stackoverflow.com/questions/2559527/non-static-variable-cannot-be-referenced-from-a-static-context?rq=1 – DigCamara Mar 10 '14 at 19:17
-
@GeorgeTomlinson Immutability isn't really the issue here. – keyser Mar 10 '14 at 19:18
-
@Keyser: Yeah, for some reason I decided to answer a different question. – George Tomlinson Mar 10 '14 at 19:20
-
This is not an error. In Java, static means "Class" member, not "Instance" member. In practice there is no "this" operator inside a static method (there is no reference to the actual object), so the only way you can reference an object inside such a method is by contructing it in this mentioned method. They are meant to be methods used by other classes without having the restriction to create an instance first. – Endrik Mar 10 '14 at 19:20
2 Answers
static variable initialized when class is loaded into JVM
on the other hand instance variable has different value for each instances and they get created when instance of an object is created either by using new()
operator or using reflection like Class.newInstance()
.
So if you try to access a non static variable without any instance compiler will complain because those variables are not yet created and they don't have any existence until an instance is created and they are associated with any instance. So in my opinion only reason which make sense to disallow non static or instance variable inside static context is non existence of instance.
Read more here

- 8,567
- 3
- 26
- 43
If you have a variable which is class-dependant and you try to reference it in a static method it won't compile due to the fact that non-static class variables need an instance to get initialized.
Static elements get initialized automatically into JVM when the class gets loaded - instance variables don't, they're initialized when an instance is created.
Take a look at some Java Docs regarding class variables, it's described in depth in the original Oracle manual. You can start by looking here for example.

- 13,653
- 10
- 56
- 109