什么时候是使用“新”的合适时机?关键词?
Java中什么时候需要使用new关键字?我知道当您创建这样的对象实例时应该使用它:
TextView textView = new TextView(this);
有时在代码中我注意到没有使用 new
并且我感到困惑.. 在这行代码中:
AssetManager assetManager = getAssets();
为什么不是这样创建 AssetManager 的实例:
AssetManager assetManager = new AssetManager();
然后将其设置为等于 getAssests()?
什么时候应该使用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);
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
当第一次显式创建对象时,可以使用 new 关键字。然后不需要使用 getter 方法 new 来获取对象,因为该对象已经存在于内存中,因此不需要重新创建。
如果您想了解新功能的更详细说明,请访问oracle 文档
如果对象为 null(这对于未初始化来说很有趣),则需要“new”关键字。
在当前情况下,这将始终打印“need 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.
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).
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"
在 Java 中,
new MyClass()
创建一个新的MyClass
的实例 并返回对其的引用。同时,声明:
定义了一个变量
foo
,它可以存储对MyClass
实例的引用,或者表示不存在的特殊值null
这样的参考。如果您没有分配任何对foo
的引用,则其默认值为null
。您当然可以将这些东西结合起来,例如像这样:
或者,等效地,像这样:
但是您不必在每次将某些内容分配给引用变量时都创建一个新实例。您也可以这样做,例如:
甚至:
请注意,在 Java 中,与 C++ 等其他语言相反,您永远不能将实际对象(的副本)分配给变量。相反,Java 对象总是通过对它们的引用来访问。当有人在 Java 中谈到“将对象分配给变量”或“将对象作为参数传递”或“从方法返回对象”时,他们实际上的意思总是指分配或传递或返回一个引用 /em> 到一个对象。
您的代码调用的方法也可以(并且经常这样做)返回对对象的引用。例如,如果您的类有一个如下所示的方法:
您可以调用它并将其返回的引用保存到如下所示的变量中:
或者像这样:
我们可以从方法声明中得知
getSomeObject()
将始终返回对MyClass
实例(或null
)的引用,但不是该实例实际来自的位置。这完全取决于 getSomeObject() 方法内的代码的作用。每次调用代码时,代码可能总是使用new MyClass()
创建一个新的MyClass
实例,并返回对其的引用,或者它可能始终返回对MyClass()
的引用。 em>相同的对象。或者,当然,它有时会返回对新对象的引用,有时会返回先前创建的对象的引用。请注意,如果为变量分配新值,则之前包含的任何变量都将被忘记。如果忘记的值恰好是某个对象的最后一个引用,那么该对象本身将被 Java 的垃圾收集器销毁。
因此,举例来说,虽然确实可能做这样的事情:
但这通常没有意义,因为您创建一个新的
MyClass
实例只是为了立即扔掉您对它的唯一引用并将其替换为其他内容。实际上,上面的代码完全等同于:唯一有意义的情况是,如果您想要创建一个新的
MyClass
实例并立即让它成为可能垃圾收集,例如因为MyClass
构造函数有一些您想要触发的副作用。但是,由于构造函数通常被认为具有任何重要副作用(或者更一般地说,除了设置新对象之外执行任何操作)的不良风格,因此您通常不应该有任何借口编写此类代码。In Java,
new MyClass()
creates a new instance ofMyClass
and returns a reference to it.Meanwhile, the declaration:
defines a variable
foo
that can store a reference to an instance ofMyClass
, or the special valuenull
that indicates the absence of such a reference. If you don't assing any reference tofoo
, its default value will benull
.You can certainly combine these things, e.g. like this:
or, equivalently, like this:
But you don't have to create a new instance every time you assign something to a reference variable. You could just as well do e.g. this:
or even:
Note that in Java, as opposed to some other languages like C++, you can never assign (a copy of) an actual object into a variable. Rather, Java objects are always accessed via references to them. When someone speaks of "assigning an object to a variable" or "passing an object as a parameter" or "returning an object from a method" in Java, what they always actually mean is assigning or passing or returning a reference to an object.
Methods that your code calls can (and often do) also return references to objects. For example, if your class had a method like this:
you could call it and save the reference it returns into a variable like this:
or like this:
We can tell from the method declaration that
getSomeObject()
will always return a reference to aMyClass
instance (ornull
), but not where that instance actually comes from. That depends entirely on what the code inside thegetSomeObject()
method does. The code might always create a newMyClass
instance withnew MyClass()
every time it's called, and return a reference to it, or it might always return a reference to the same object. Or, of course, it could sometimes return a reference to a new object, and sometimes to a previously created one.Note that, if you assign a new value to a variable, whatever the variable contained before will be forgotten. If the forgotten value happens to be the last reference to some object, then that object itself will be destroyed by Java's garbage collector.
So, for example, while it's certainly possible to do something like this:
that normally makes no sense, since you'd be creating a new
MyClass
instance just to immediately throw away your only reference to it and replace it with something else. In effect, the code above is exactly equivalent to:The only time that could even remotely make sense would be if you wanted to create a new
MyClass
instance and immediately let it be garbage collected, e.g. because theMyClass
constructor had some side effect that you wanted to trigger. But since it's usually considered bad style for constructors to have any non-trivial side effects (or, more generally, to do anything besides setting up the new object), you shouldn't normally have any excuse for writing such code.在 java 中,你总是必须使用 new 来实例化对象(嗯,几乎总是如此)。使用
getAssests()
您可以检索已创建的资产。我猜你的问题来自c++,其中new
分配动态内存,但由于java只有动态对象,所以总是需要new。In java you always have to use
new
to instantiate objects (well, almost always). WithgetAssests()
you retrieve an already created one. I guess your question comes from c++ wherenew
allocates dynamic memory, but since java has only dynamic objects, new is always needed.当您调用函数的构造函数时,会使用 new。 getAssets() 返回一个 AssetManager,它不需要创建一个新的。
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.
通过使用
new
,您可以为对象分配内存。使用
getXXX()
用于获取已分配的现有对象。By using
new
you allocate memory for the object.Using a
getXXX()
is used to get an existing object which is already allocated.new
始终用于创建新对象。这
只是将从方法
getAssets()
返回的值分配给引用assetManager
。[编辑]
我对
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:
由于您用 [android] 标记了这一点,我猜测您的代码位于
Activity
或Service
内部。在本例中,getAssets()
是您要扩展的类的方法。因此,您实际上并没有创建它,而是要求现有代码为您提供对已存在内容的引用。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.请注意 TextView 中的大写字母,以及 getAssets 中缺少的大写字母。 getAssets 不是像 TextView 这样的类,它是一个返回对象的方法。正如许多其他人提到的那样,您的资产已经存在。
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.