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!
Since you flagged this with [android], I'm guessing your code is inside of an
Activity
orService
. 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.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.
By using
new
you allocate memory for the object.Using a
getXXX()
is used to get an existing object which is already allocated.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.
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.
So to fix it, you would do something like:
And under those circumstances we will always see "does NOT need neW"
new
is always used to create new object.this
is just assignation a value returned from method
getAssets()
to referenceassetManager
.[edit]
i lied about
new
it is possible to do something like this:and also you can use reflection: