16

When is it necessary to use the new keyword in Java. I know you are supposed to use it when you create an instance of an object like this:

TextView textView = new TextView(this);

Sometimes in code I notice that new isn't used and I get confused.. In this line of code:

    AssetManager assetManager = getAssets();

Why isn't an instance of the AssetManager created like this:

AssetManager assetManager = new AssetManager();

then it is set equal to getAssests()?

When should new be used?

Thanks!

ahodder
  • 11,060
  • 14
  • 63
  • 109
foobar5512
  • 2,190
  • 5
  • 31
  • 52

8 Answers8

12

You use the new keyword when an object is being explicitly created for the first time. Then fetching an object using a getter method new is not required because the object already exists in memory, thus does not need to be recreated.

if you want a more detailed description of new visit the oracle docs

An object will need the 'new' keyword if it is null (which is fancy for not initialized).

EDIT:

This will always print "needs new" under the current circumstances.

Object mObj = null;
if (mObj == null)
    System.out.println("needs new");
else
    System.out.println("does NOT need new");

OUTPUTS: needs new

So to fix it, you would do something like:

Object mObj = new Object();
if (mObj == null)
    System.out.println("needs new");
else
    System.out.println("does NOT need new");
OUTPUTS: does NOT need new

And under those circumstances we will always see "does NOT need neW"

ahodder
  • 11,060
  • 14
  • 63
  • 109
  • When you try to reference it, it will be null. You can check that by something like (refer to my update) – ahodder Jan 06 '12 at 22:42
  • 1
    You get this information from the documentation - or experience. For example Managers are often used as singletons (or s.th. similar), so there is only one instance. This kind of classes you don't create, but there is a function to retrieve the object. – Philipp Wendt Jan 06 '12 at 22:44
  • While the first paragraph of this answer is essentially correct, the rest is factually incorrect (a null reference does not "need new" to become non-null; it just needs to have an object reference assigned to it) and does nothing to address the OP's confusion about code like `assetManager = getAssets()` not needing `new`. IMO, the edit that added it should be rolled back. – Ilmari Karonen Oct 29 '17 at 17:01
  • Why isn't 'new' required (or accepted) when creating this new object:- `LinearLayout rootView = (LinearLayout)findViewById(R.id.rootView);` – Markus Nov 27 '18 at 22:18
10

In Java, new MyClass() creates a new instance of MyClass and returns a reference to it.

Meanwhile, the declaration:

MyClass foo;

defines a variable foo that can store a reference to an instance of MyClass, or the special value null that indicates the absence of such a reference. If you don't assing any reference to foo, its default value will be null.

You can certainly combine these things, e.g. like this:

MyClass foo;           // define a variable foo that can store an object reference
foo = new MyClass();   // create a new object and assign a reference to it to foo

or, equivalently, like this:

MyClass foo = new MyClass();  // combined variable definition and assignment

But you don't have to create a new instance every time you assign something to a reference variable. You could just as well do e.g. this:

MyClass foo, bar;      // define two reference variables, foo and bar
foo = new MyClass();   // create a new object and assign a reference to it to foo
bar = foo;             // now foo and bar point to the same object

or even:

MyClass foo = new MyClass(), bar = foo;  // same, but shorter

Note that in Java, as opposed to some other languages like C++, you can never assign (a copy of) an actual object into a variable. Rather, Java objects are always accessed via references to them. When someone speaks of "assigning an object to a variable" or "passing an object as a parameter" or "returning an object from a method" in Java, what they always actually mean is assigning or passing or returning a reference to an object.


Methods that your code calls can (and often do) also return references to objects. For example, if your class had a method like this:

private MyClass getSomeObject() {
    // ...some code here...
}

you could call it and save the reference it returns into a variable like this:

MyClass foo;
foo = getSomeObject();

or like this:

MyClass foo = getSomeObject();

We can tell from the method declaration that getSomeObject() will always return a reference to a MyClass instance (or null), but not where that instance actually comes from. That depends entirely on what the code inside the getSomeObject() method does. The code might always create a new MyClass instance with new MyClass() every time it's called, and return a reference to it, or it might always return a reference to the same object. Or, of course, it could sometimes return a reference to a new object, and sometimes to a previously created one.


Note that, if you assign a new value to a variable, whatever the variable contained before will be forgotten. If the forgotten value happens to be the last reference to some object, then that object itself will be destroyed by Java's garbage collector.

So, for example, while it's certainly possible to do something like this:

MyClass foo = new MyClass();  // create a new object and assign (a reference to) it to foo
foo = getSomeObject();        // forget the previous content of foo and replace it with whatever getSomeObject() returns

that normally makes no sense, since you'd be creating a new MyClass instance just to immediately throw away your only reference to it and replace it with something else. In effect, the code above is exactly equivalent to:

new MyClass();       // create a new object and throw away(!) the reference to it
MyClass foo = getSomeObject();  // assign whatever getSomeObject() returns to foo

The only time that could even remotely make sense would be if you wanted to create a new MyClass instance and immediately let it be garbage collected, e.g. because the MyClass constructor had some side effect that you wanted to trigger. But since it's usually considered bad style for constructors to have any non-trivial side effects (or, more generally, to do anything besides setting up the new object), you shouldn't normally have any excuse for writing such code.

Ilmari Karonen
  • 44,762
  • 9
  • 83
  • 142
9

In java you always have to use new to instantiate objects (well, almost always). With getAssests() you retrieve an already created one. I guess your question comes from c++ where new allocates dynamic memory, but since java has only dynamic objects, new is always needed.

zeller
  • 4,574
  • 2
  • 19
  • 35
4

The new is used when you call the constructor for a function. getAssets() returns an AssetManager, it doesn't need to create a new one.

PearsonArtPhoto
  • 35,989
  • 16
  • 107
  • 136
  • I like this answer the most. This is what I learned in university. You use new to call constructor of a function. – MaXi32 Apr 26 '21 at 13:37
3

new is always used to create new object.

this

AssetManager assetManager = getAssets();

is just assignation a value returned from method getAssets() to reference assetManager.

[edit]

i lied about new it is possible to do something like this:

Foo.class.newInstance();

and also you can use reflection:

Foo.class.getDeclaredConstructors(Class[] parameterTypes).newInstance(arguments);
czajah
  • 353
  • 3
  • 12
2

By using new you allocate memory for the object.

Using a getXXX() is used to get an existing object which is already allocated.

Philipp Wendt
  • 2,338
  • 1
  • 13
  • 17
2

Since you flagged this with [android], I'm guessing your code is inside of an Activity or Service. In this case, getAssets() is a method of the class you are extending. So you aren't actually creating it, you are asking the existing code to give you a reference to what already exists.

Argyle
  • 3,226
  • 21
  • 42
0

notice the capital letter in TextView, and the lack of it in getAssets. getAssets isn't a class like TextView, it's a method returning an object. And like many others mentioned, your asset already exists.

keyser
  • 17,711
  • 16
  • 54
  • 93