This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Hi, I am new to Java. What does this statement really mean ??
"You must keep in mind that these static(global like )thing eg- pi , are the exception rather than the rule in Java. They represent a very special case, where you have multiple/instances."
Have the determination of mirror which never fails to reflect in spite of being broken into pieces.<br /> <br />Kiss the hands you cannot bite.<br /> <br />An Optimist is one who starts taking a bath when he accidentally falls into the water.
A static member is one which is shared between all instances of the class, and exists even when there aren't any instances. There are several places where they can be used:
Constants: the example given, "pi" appears in the java.lang.Math class as "public static final double PI = 3.141592653589793". This is a value which is always the same, so there need only be one copy of them. You can use a static final field instead of a global method; it can be public because it can't be changed.
Counters and similar. You can use a static variable, which is shared between instances as a counter, as in the serial number example in the link which Abdulla Mamuwala gave earlier.
You can use a static method whenever there is no information which might change any of the fields of an object. Example: if you want the logarithm of a number, you send a number to the log() method and it gives you a result. No need to alter anything else. Look at the Math class: all its methods are static.
Example: you want a factory method which creates an instance of something: tell it what to create and it returns the instance. No change to anything else in an instance.Static members are less common than instance members, and that true constant values like PI are even less common, but if you look through the API you find quite a lot of static fields and methods.
Joined: Feb 28, 2008
Thank You everybody. I got it now. [ March 03, 2008: Message edited by: Shivit Agarwal ]