This week's book giveaway is in the Android forum.
We're giving away four copies of Head First Android and have Dawn & David Griffiths on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Using getInstance() and newInstance() methods Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Head First Android this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Using getInstance() and newInstance() methods" Watch "Using getInstance() and newInstance() methods" New topic

Using getInstance() and newInstance() methods

Rajdeep Biswas
Ranch Hand

Joined: Mar 26, 2012
Posts: 187

Where and how to use those methods correctly? Why not constructors?

Thanks a million

The biggest gamble will be to ask a question whose answer you know in that it will challenge your theory |
Koen Aerts
Ranch Hand

Joined: Feb 07, 2012
Posts: 344

The where and how depends on the specific class you're trying to use. For instance for a Calendar you would use Calendar.getInstance(). As to the why, have a look at the following:
Winston Gutkowski

Joined: Mar 17, 2011
Posts: 8661

Rajdeep Biswas wrote:Where and how to use those methods correctly? Why not constructors?

Other than Koen's link, Effective Java also has a very good section on using factories.

Just a few reasons for using factories are:
1. The method has a meaningful name.
2. A factory doesn't necessarily have to return you a new object.
3. A factory doesn't even have to return you an object of the specified type. It can, for example, return you an anonymous subclass (sometimes very useful).


Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here
subject: Using getInstance() and newInstance() methods
It's not a secret anymore!