aspose file tools*
The moose likes Beginning Java and the fly likes static variables are not accesed by class instances???? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "static variables are not accesed by class instances????" Watch "static variables are not accesed by class instances????" New topic
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: 2711
    
    5

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: 2711
    
    5

Great !!
 
Consider Paul's rocket mass heater.
 
subject: static variables are not accesed by class instances????
 
Similar Threads
Regarding Method Shadowing
Use of static modifier
why can't a function be called from a static context
Static method modifier question
problem with static counter