何时适合使用'new'关键字? [英] When is the appropriate time to use the 'new' keyword?
问题描述
何时需要在Java中使用 new
关键字。我知道你应该在创建像这样的对象的实例时使用它:
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);
有时在代码中我注意到 new
isn使用了,我感到困惑..
在这行代码中:
Sometimes in code I notice that new
isn't used and I get confused..
In this line of code:
AssetManager assetManager = getAssets();
为什么不像这样创建AssetManager的实例:
Why isn't an instance of the AssetManager created like this:
AssetManager assetManager = new AssetManager();
然后设置为等于getAssests()?
then it is set equal to getAssests()?
何时应该使用 new
?
谢谢!
推荐答案
在第一次显式创建对象时使用new关键字。然后不需要使用getter方法new获取对象,因为该对象已经存在于内存中,因此不需要重新创建。
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.
如果你想要更详细的描述新访问 oracle docs
if you want a more detailed description of new visit the oracle docs
一个对象需要'new'关键字,如果它是null(这对于未初始化很有意义)。
An object will need the 'new' keyword if it is null (which is fancy for not initialized).
编辑:
在当前情况下,这将始终打印需要新的。
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"
这篇关于何时适合使用'new'关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!