Im just a beginner .. My query is .. We can refer static members using reference variables.. But reference variable contains address of object which contains non-static members of the class .. How is it working?
-
It basically comes to the idea that everything is a pointer to somewhere in memory. You're basically pointing your "instance" or "reference" variable to the memory location of the `static` field. By it's nature, these address space cannot be modified. I'm hoping some more how is more articulate than I can make that clearer :P – MadProgrammer Sep 25 '13 at 05:52
-
So it refers in the static pool ? – Smrithi Komalan Sep 25 '13 at 05:54
-
[*This*](http://stackoverflow.com/questions/8387989/where-is-a-static-method-and-a-static-variable-stored-in-java-in-heap-or-in-sta) might help (to confus you further ;)) – MadProgrammer Sep 25 '13 at 05:56
-
@MadProgrammer I believe you err when you say that the address space cannot be modified. As long as the variable is not `static final` it should be modifiable. – Eric Tobias Sep 25 '13 at 06:04
-
@RohitJain I believe the question is sufficiently different while the answer relates to the same mechanics. – Eric Tobias Sep 25 '13 at 06:06
2 Answers
When you are referencing a class (not an object mind you) as for example MyLasterGun
then the resources for that class will be located and loaded. Part of the resources for the class are its variables. Non-static variables are instantiated once the class is instantiated but static
variables are instantiated as soon as the class is loaded. Consider this code:
public class MyLaserGun
{
public static String target = "Major Movie Metropolis";
public Timer countdown;
public void MyLasterGun()
{
countdown = new Timer();
}
}
public class FortressOfDoom
{
private String target;
public void FortressOfDoom()
{
target = MyLaserGun.target;
// To access the timer, an actual instance must be created
MyLaserGun pewpew = new MyLaserGun();
pewpew.countdown.cancel();
}
}
You could access the target by calling MyLaserGun.target
but you can't access the countdown unless you instantiated the class creating a new object.
Also, do not confuse static
variables, which you can edit just fine, with static final
variables which are constants and cannot be changed.
More information on when static variables are initialised can be found in When does static class initialization happen?.
Update Consider the updated example.

- 1
- 1

- 3,225
- 4
- 32
- 50
Static member means its property of class. where non-static member means property of object.
take an example of Bird class so if i say canFly = true is static property of Bird class.
but say suppose now you want to describe only those Bird who can not fly then you can use
Bird penguin = new Bird();
penguin.canFly= false;//canFly is static variable.
that means now you are decribing only those bird what cannot fly.
where as
penguin.homeTown = coldArea; // is non-static property.