When is the appropriate time to use the 'new&#

2020-05-23 17:57发布

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!

8条回答
我想做一个坏孩纸
2楼-- · 2020-05-23 18:14

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.

查看更多
太酷不给撩
3楼-- · 2020-05-23 18:15

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.

查看更多
4楼-- · 2020-05-23 18:17

By using new you allocate memory for the object.

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

查看更多
叼着烟拽天下
5楼-- · 2020-05-23 18:19

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.

查看更多
Lonely孤独者°
6楼-- · 2020-05-23 18:25

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"

查看更多
家丑人穷心不美
7楼-- · 2020-05-23 18:27

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);
查看更多
登录 后发表回答