This page contains an archived post to the Design Forum (formerly called the Flexible Java Forum) made prior to February 25, 2002.
If you wish to participate in discussions, please visit the new
Classes as objects and class objects
Posted by Dan Shellman on September 05, 2000 at 5:03 PM
After reading Bill's article, I'm a little disappointed. First,
I disagree overall with his approach. In addition, though a
little nit-picky, there was one inaccuracy in the article.
The inaccuracy has to do with the garbage collection of classes.
Though technically correct, his wording was a little confusing.
Bill states that a classes gets garbage collected when there
are no more references to it (like any object). This is correct,
though misleading. The reason is that if a classloader has a
reference to the class, then the class will not be garbage-
collected. The classloaders reference to a class constitutes
a valid reference, which means that when the system class loader
loads a class, the class will never be unloaded until the java
As for the general statement that using classes as objects is
not object oriented and should not be done, I disagree. There
are several places in which it's not only appropriate, but also
useful. However, the statements made about applets is certainly
accurate (that is, static class data within applets should be
minimized in the very least).
A good example of a class used as an object is a database connection
pool. There is no value in instantiating a single instance and
then providing a static method that returns that reference. Why
not just provide direct static methods that act as passthroughs
to the actual object? For example:
public class Foo
private static Foo myFoo = new Foo();
private int myInt = 0;
public static int getStuff()
Though a contrived example, this code shows how a Singleton
can (and IMHO should) be implemented. If loaded by the system
class loader, there is no concern that the class will be lost.
There is no need to "get access" to the only instance that
Where else do Singletons like the above get used? Try: centralized
configuration; caching; connection pooling; thread pooling; etc.
These Singletons act as centralized servers for varying
services, just like CORBA servers typically provide a centralized
object that gives access to other, more detailed, objects.
As for threading issues, adding a synchronized block around the
single instance is usually a good start (obviously, each singleton
may be different).
As for subclassing...well, usually, these services aren't
subclassed. And if they are, in addition to the singleton
pattern, a factory pattern gets used.