views:

78

answers:

3

Hi, Is calling Class.getInstance() equivalent to new Class()? I know the constructor is called for the latter, but what about getInstance? Thanks.

+1  A: 

Absolutely (usually) not.

getInstance is the static method often used with the Singleton Pattern in Java. The new keyword actually creates a new object. At some point there must be a new (although there are a few other methods to instantiate new objects) to actually create the object that getInstance returns.

pst
+4  A: 

There is no such method as Class#getInstance(). You're probably confusing it with Class#newInstance(). And yes, this does exactly the same as new on the default constructor. Here's an extract of its Javadoc:

Creates a new instance of the class represented by this Class object. The class is instantiated as if by a new expression with an empty argument list. The class is initialized if it has not already been initialized.

In code,

Object instance = Object.class.newInstance();

is the same as

Object instance = new Object();

The Class#newInstance() call actually follows the Factory Method pattern.


Update: seeing the other answers, I realize that there's some ambiguity in your question. Well, places where a method actually named getInstance() is been used often denotes an Abstract Factory pattern. It will "under the hoods" use new or Class#newInstance() to create and return the instance of interest. It's just to hide all the details about the concrete implementations which you may not need to know about.

Further you also see this methodname often in some (mostly homegrown) implementations of the Singleton pattern.

See also:

BalusC
Actually, he specifically said *Class.getInstance()*, so I think your first thought that he is confused is the correct one.
Software Monkey
@Software: Yes, but he added a tag `abstract-class`. Ambiguity galore :)
BalusC
+1  A: 

In the context of an abstract class, a getInstance() method may represent the factory method pattern. An example is the abstract Calendar class, which includes static factory methods and a concrete subclass.

trashgod