Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is the appropriate time to use the 'new' keyword?

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!

like image 964
foobar5512 Avatar asked Jan 06 '12 22:01

foobar5512


People also ask

What is new keyword used for?

The new keyword in JavaScript: The new keyword is used to create an instance of a user-defined object type and a constructor function. It is used to constructs and returns an object of the constructor function.

When should the this keyword be used?

The this keyword refers to the current object in a method or constructor. The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter).

What is the use of new keyword in C++?

When new is used to allocate memory for a C++ class object, the object's constructor is called after the memory is allocated. Use the delete operator to deallocate the memory allocated by the new operator.

When the object will be created using new keyword?

Instantiation: The new keyword is a Java operator that creates the object. As discussed below, this is also known as instantiating a class. Initialization: The new operator is followed by a call to a constructor. For example, Point(23, 94) is a call to Point's only constructor.


1 Answers

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"

like image 198
ahodder Avatar answered Oct 19 '22 22:10

ahodder