File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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 Soft Skills this week in the Jobs Discussion 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: 8419
    
  23

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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Using getInstance() and newInstance() methods