wood burning stoves 2.0*
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 Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Using getInstance() and newInstance() methods" Watch "Using getInstance() and newInstance() methods" New topic
Author

Using getInstance() and newInstance() methods

Rajdeep Biswas
Ranch Hand

Joined: Mar 26, 2012
Posts: 186

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 | www.TechAspire.blogspot.in
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: http://en.wikipedia.org/wiki/Factory_method_pattern
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 7492
    
  18

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).

Winston

Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here
 
Don't get me started about those stupid light bulbs.
 
subject: Using getInstance() and newInstance() methods
 
Similar Threads
Lucene - get TermVector positions
How do OBJECTS pass messages in Java?
Inheritance of all members
servlet security
What is the logic behind calls like JOptionPane.method()