Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between calling new and getInstance()

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

like image 423
SIr Codealot Avatar asked Jul 03 '10 03:07

SIr Codealot


1 Answers

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:

  • Real world examples of GoF design patterns.
like image 89
BalusC Avatar answered Oct 08 '22 16:10

BalusC