Is calling Class.getInstance() equivalent to new Class()?
I know the constructor is called for the latter, but what about getInstance()?
Thanks.
Is calling Class.getInstance() equivalent to new Class() ? I know the constructor is called
Share
There is no such method as
Class#getInstance(). You’re probably confusing it withClass#newInstance(). And yes, this does exactly the same asnewon the default constructor. Here’s an extract of its Javadoc:In code,
is the same as
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" useneworClass#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: