File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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 Android Security Essentials Live Lessons 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: 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 |
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: 7552

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
I agree. Here's the link:
subject: Using getInstance() and newInstance() methods
Similar Threads
servlet security
Lucene - get TermVector positions
How do OBJECTS pass messages in Java?
Inheritance of all members
What is the logic behind calls like JOptionPane.method()