Alex Rivera | Logout

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

Asked 2012-01-17T03:14:05.900
14

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?

Edit
Report

1 Answer

2

In your examples they are equivalent and there is no real reason to chose one over the other. However, using newInstance is commonly used if to perform some initialization prior to handing back an instance of the class. If every time you request a new instance of the class by calling its constructor, you end up setting a bunch of instance variables before you can use the object, then it would make more sense to have the newInstance method perform that initialization and return to you an object that's ready to use.

For example, Activitys and Fragments aren't initialized in their constructors. Instead, they are generally initialized during onCreate. Therefore, it's common practice for the newInstance method to accept whatever parameters the object will need to use during initialization, and it stores them in a Bundle that the object can read from later. An example of this can be seen here:

Sample class with newInstance method

answered 2012-01-17T03:26:16.113

Your Answer