File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Static methods and variables Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Static methods and variables" Watch "Static methods and variables" New topic

Static methods and variables

aakash bhatt
Ranch Hand

Joined: Jan 09, 2003
Posts: 182
What is the use of static method and variables and when should we use in Java
And as it is not part of Object but a member of class directly. Is it good to use in OOPS
Ellen Zhao
Ranch Hand

Joined: Sep 17, 2002
Posts: 581
Good question.
Correct me if I am wrong.
Static methods and fields are often dispised in OOP, but they do have valid usages. Say, in the Facade pattern, you may want to write classes contain merely static methods to make the swing code much easier to use. These static methods can be seen as "macros" of the wordy "raw" swing code. For example,

so that, other classes can invoke these methods without instantiate the SwingFacade class.
Sometimes you may want to make classes contain merely constants, be it mathematical constants or just configuration of your project, never put them in interface, but make them static field in classes, again you can use these constants without instantiate the "database" class. In the comming J2SE 1.5, you simply say like this:

pay attention here the constant is the name of a package and the Configuration is the name of a class.
And, if you write simple programmes for numerical computing, you can use static methods and fields too. But if the computing goes complex, say, solving linear equation system by means of Cholesky decomposition, try to consider better design of your code, don't put everything in one class!
Does that help?

Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Static variables are appropriate when there really should be only one of something. Caches and pools often are or use static variables because we want one cache that can hold any number of other objects.
I also use them for low-level class lifecycle stuff, like keeping a count of instances or giving each instance a unique id for logging purposes.

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
I agree. Here's the link:
subject: Static methods and variables
It's not a secret anymore!