File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static methods and variables

 
aakash bhatt
Ranch Hand
Posts: 182
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Regards,
Pradeep
 
Ellen Zhao
Ranch Hand
Posts: 581
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?

Regards,
Ellen
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic