Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static variables are not accesed by class instances????

 
suavedeep kaur
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Nathan Leniz
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Amit Ghorpade
Bartender
Posts: 2854
10
Fedora Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
suavedeep kaur
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That was great explanation sir i got the point

thanks
 
Amit Ghorpade
Bartender
Posts: 2854
10
Fedora Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Great !!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic