Win a copy of Head First Agile this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Static members  RSS feed

 
Vidya sagari
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is a very basic question but I don't understand the whole concept of static member. Why is it said that static members are independent?
 
Anurag Verma
Ranch Hand
Posts: 170
Hibernate Spring Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Static members are independent, lets define independency here.

For static variables, the space for a static variable is not allocated inside the instance of class. ie if you create an object of a particular class with some static & non static variables, all non static variables will get space inside every instance, but static variables get space in the JVM memory outside the instance & has single presence. static variable will be same for all the instances of class.

For static methods, you can call them directly using the class name & you don't need an instance for calling. the "Function Activation Record" or stack frame creation for all the methods is same & never changes.

So basically the term "independant" means independent of the "instance" that you have or may create. Hope that answers...
 
Campbell Ritchie
Marshal
Posts: 55799
164
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Vidya sagari wrote:. . . Why is it said that static members are independent?
That is a good question. I suspect it is because whoever said that didn't understand static members.

A static member belongs to the class not the object. Your default behaviour is to make everything “instance”, though the compiler confusingly calls that “non‑static”. If you do not have a good explanation for making something static, it is a mistake. If the explanation is because the compiler complained about “non‑static”, then it is still a mistake. It is sometimes useful to have a static field because there is exactly one copy of the field irrespective of however many instances there are:-
1 instance, 1 copy of static field.
2 instances, 1 copies of static field.
1000000 instances, 1 copies of static field.
No instances, 1 copies of static field.
So it is usual to make constants static because you always want one copy:-
public static final double ABSOLUTE_ZERO = -273.15;
Classes with all static members are often made uninstantiable as described in the Java® Language Specification.

There is a very dubious classification of methods around. Look here. It gives hints about when you might want to make a method static.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!