rex rex - 1 year ago 76
Java Question

What is the difference between "new A()" and "A.newInstance()"?

When should I prefer one over the other? What is the purpose of the method shown below?

class A {
public static A newInstance() {
A a = new A();
return a ;

Can someone explain to me the differences between these two calls?

Answer Source

newInstance() is often used as a way to instantiate an object without directly calling the object's default constructor. For example, it is often used to implement a Singleton design pattern:

public class Singleton {
    private static final Singleton instance = null;

    // make the class private to prevent direct instantiation.
    // this forces clients to call newInstance(), which will
    // ensure the class' Singleton property.
    private Singleton() { } 

    public static Singleton newInstance() {
        // if instance is null, then instantiate the object by calling
        // the default constructor (this is ok since we are calling it from 
        // within the class)
        if (instance == null) {
            instance = new Singleton();
        return instance;

In this case, the programmer forces the client to call newInstance() to retrieve an instance of the class. This is important because simply providing a default constructor would allow the client access to multiple instances of the class (which goes against the Singleton property).

In the case of Fragments, providing a static factory method newInstance() is good practice since we often want to add initialization arguments to the newly instantiated object. Rather than having the client call the default constructor and manually set the fragment arguments themselves, we can provide a newInstance() method that does this for them. For example,

public static MyFragment newInstance(int index) {
    MyFragment f = new MyFragment();
    Bundle args = new Bundle();
    args.putInt("index", index);
    return f;

Overall, while the difference between the two is mostly just a matter of design, this difference is really important because it provides another level of abstraction and makes code a lot easier to understand.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download