It's not a secret anymore!
The moose likes Java in General and the fly likes Static Methods and Classes (Best Practices) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Static Methods and Classes (Best Practices)" Watch "Static Methods and Classes (Best Practices)" New topic

Static Methods and Classes (Best Practices)

Gabriel Cane
Ranch Hand

Joined: Mar 27, 2001
Posts: 39
This is not a "how to" question but a "best practices" question.
Under what circumstances is it best to use a static class with static methods and when is it best to use a non-static class with non-static and/or static methods. I want to know from the point of view of program efficiency and memory conservation. This class does not have any variables in it. It is simply called by other classes and is passed paramaters in order to provide specific functionality to other classes.
Will keeping the class to one instance actually help conserve memory, or will it increase the load on that particular class, given that many different instances of other classes are accessing it?

Sun Certified Programmer for the Java 2 Platform
Michael Ernest
High Plains Drifter

Joined: Oct 25, 2000
Posts: 7292

Classes like these are often called "utility classes," and they generally perform one or two purposes. One, like java.Math, is to offer services for which objects, overriding and subclassing add marginal, if any, value. Sure, someone may want to override Math.rand(), say, but the class writer doesn't bother changing thr nature of his interface to accommodate that. It's far better that Math functions be used as intended -- as a static resource.
Factory methods -- which construct objects and return them to the caller -- also make good candidates for static invocation. You can read more about their intended uses from a wide variety of sources on design patterns.
There's no question that static classes reduce the amount of memory required by a class, if only because they need no further allocated memory for object instances. There's no meaningful argument, I believe, that they add to the process footprint; they'd add the same overhead if they were non-static.
Michael Ernest, co-author of: The Complete Java 2 Certification Study Guide

Make visible what, without you, might perhaps never have been seen.
- Robert Bresson
Bill Siggelkow
Ranch Hand

Joined: Jun 27, 2001
Posts: 57
Check out this article from JavaWorld

Bill Siggelkow
Jade Cove Solutions
I agree. Here's the link:
subject: Static Methods and Classes (Best Practices)
It's not a secret anymore!