Reference of non static variable

72 views Asked by At

If I refer non static variable with class name, when one object is there, why it is compile-time error?

I have created one object so one set of non-static variable is there in Heap Area. So if I refer that non-static variable with class name, there is only one non-static variable, so it can use that.

3

There are 3 answers

0
Dakshinamurthy Karra On

Event if it makes sense, how does the compiler to know that you created only a single instance? static variables belongs to the Class objects (incidentally they are instances of class Class).

0
Kayaman On

First because that's how it is.

Secondly because at compile time nobody knows whether there will be 0, 1 or a million instances. Besides it would result in extremely confusing code, when you couldn't tell if something is referring to a static variable or the "single instance variable".

8
Manish Kumar Sharma On

Lets say you could do that and there was no compile time error, How could the compiler know, which variable reference when there are more than 1 instances? Putting your theory in practice just for 1 instance would result in nonsensical looking complex code.

If you want more details and need the programmer's perspective, go read the Java Language specification and JVM specification to see how the memory management is specified.

https://docs.oracle.com/javase/specs/