| Author |
static variables are not accesed by class instances????
|
suavedeep kaur
Ranch Hand
Joined: Jun 02, 2008
Posts: 36
|
|
As it is said in one of the post also that * static variables are class variables * They are accessed only by class and not class instances * static variables are accessible from static methods and classname class StaticDemo{ static int a=90; static int b; static { System.out.println("Static block initialised "); b=a/2; } static void meth(){ System.out.println("the value of a and b is :" + a + " " + b ); } } class StaticTry{ public static void main(String args[]){ StaticDemo ob = new StaticDemo(); ob.meth(); System.out.println(ob.b); StaticDemo.meth(); } } but in the above program i can access from class instance also Why ? please explain as i am a beginner
|
Suavedeep kaur
SCJP
|
 |
Nathan Leniz
Ranch Hand
Joined: Nov 26, 2006
Posts: 132
|
|
Static means it belongs to the class, not an instance. If I have a class called Animals with a static variable called legs, I can make 20 instances of Animals but the legs aren't unique to each one. Give the following a try... We created 3 different TestStatic instances, but changing the value in the 3rd TestStatic object also affected 1 and 2. This should illustrate it.
|
The very existence of flamethrowers proves that at some time, some where, some place, someone once said to themselves "I'd really like to set those people on fire over there, but I just can't get close enough".
|
 |
Amit Ghorpade
Bartender
Joined: Jun 06, 2007
Posts: 2552
|
|
This one is a bit tricky
ob.meth();
in the above line it looks that you are using the object ob to call the static method. But actually behind the scenes, the class itself is being used to invoke the static method. the convention you used to call the method is allowed but not recommended. See this for more information. Hope this helps
|
SCJP, SCWCD.
|Asking Good Questions|
|
 |
suavedeep kaur
Ranch Hand
Joined: Jun 02, 2008
Posts: 36
|
|
That was great explanation sir i got the point thanks
|
 |
Amit Ghorpade
Bartender
Joined: Jun 06, 2007
Posts: 2552
|
|
Great !!
|
 |
 |
|
|
subject: static variables are not accesed by class instances????
|
|
|