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!
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.
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).
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.
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With