什么时候是使用“新”的合适时机?关键词?

发布于 2024-12-25 06:06:15 字数 412 浏览 2 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

默嘫て 2025-01-01 06:06:15

当第一次显式创建对象时,可以使用 new 关键字。然后不需要使用 getter 方法 new 来获取对象,因为该对象已经存在于内存中,因此不需要重新创建。

如果您想了解新功能的更详细说明,请访问oracle 文档

如果对象为 null(这对于未初始化来说很有趣),则需要“new”关键字。

在当前情况下,这将始终打印“need new”。

Object mObj = null;
if (mObj == null)
    System.out.println("needs new");
else
    System.out.println("does NOT need new");

OUTPUTS: needs new

因此,要解决此问题,您可以执行以下操作:

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

在这种情况下,我们总是会看到“不需要新的”

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.

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"

迷你仙 2025-01-01 06:06:15

在 Java 中,new MyClass() 创建一个新的MyClass 的实例 并返回对其的引用。

同时,声明:

MyClass foo;

定义了一个变量foo,它可以存储对MyClass实例的引用,或者表示不存在的特殊值null这样的参考。如果您没有分配任何对 foo 的引用,则其默认值为 null

您当然可以将这些东西结合起来,例如像这样:

MyClass foo;           // define a variable foo that can store an object reference
foo = new MyClass();   // create a new object and assign a reference to it to foo

或者,等效地,像这样:

MyClass foo = new MyClass();  // combined variable definition and assignment

但是您不必在每次将某些内容分配给引用变量时都创建一个新实例。您也可以这样做,例如:

MyClass foo, bar;      // define two reference variables, foo and bar
foo = new MyClass();   // create a new object and assign a reference to it to foo
bar = foo;             // now foo and bar point to the same object

甚至:

MyClass foo = new MyClass(), bar = foo;  // same, but shorter

请注意,在 Java 中,与 C++ 等其他语言相反,您永远不能将实际对象(的副本)分配给变量。相反,Java 对象总是通过对它们的引用来访问。当有人在 Java 中谈到“将对象分配给变量”或“将对象作为参数传递”或“从方法返回对象”时,他们实际上的意思总是指分配或传递或返回一个引用 /em> 到一个对象。


您的代码调用的方法也可以(并且经常这样做)返回对对象的引用。例如,如果您的类有一个如下所示的方法:

private MyClass getSomeObject() {
    // ...some code here...
}

您可以调用它并将其返回的引用保存到如下所示的变量中:

MyClass foo;
foo = getSomeObject();

或者像这样:

MyClass foo = getSomeObject();

我们可以从方法声明中得知 getSomeObject()将始终返回对 MyClass 实例(或 null)的引用,但不是该实例实际来自的位置。这完全取决于 getSomeObject() 方法内的代码的作用。每次调用代码时,代码可能总是使用 new MyClass() 创建一个新的 MyClass 实例,并返回对其的引用,或者它可能始终返回对 MyClass() 的引用。 em>相同的对象。或者,当然,它有时会返回对新对象的引用,有时会返回先前创建的对象的引用。


请注意,如果为变量分配新值,则之前包含的任何变量都将被忘记。如果忘记的值恰好是某个对象的最后一个引用,那么该对象本身将被 Java 的垃圾收集器销毁。

因此,举例来说,虽然确实可能做这样的事情:

MyClass foo = new MyClass();  // create a new object and assign (a reference to) it to foo
foo = getSomeObject();        // forget the previous content of foo and replace it with whatever getSomeObject() returns

但这通常没有意义,因为您创建一个新的MyClass实例只是为了立即扔掉您对它的唯一引用并将其替换为其他内容。实际上,上面的代码完全等同于:

new MyClass();       // create a new object and throw away(!) the reference to it
MyClass foo = getSomeObject();  // assign whatever getSomeObject() returns to foo

唯一有意义的情况是,如果您想要创建一个新的 MyClass 实例并立即让它成为可能垃圾收集,例如因为 MyClass 构造函数有一些您想要触发的副作用。但是,由于构造函数通常被认为具有任何重要副作用(或者更一般地说,除了设置新对象之外执行任何操作)的不良风格,因此您通常不应该有任何借口编写此类代码。

In Java, new MyClass() creates a new instance of MyClass and returns a reference to it.

Meanwhile, the declaration:

MyClass foo;

defines a variable foo that can store a reference to an instance of MyClass, or the special value null that indicates the absence of such a reference. If you don't assing any reference to foo, its default value will be null.

You can certainly combine these things, e.g. like this:

MyClass foo;           // define a variable foo that can store an object reference
foo = new MyClass();   // create a new object and assign a reference to it to foo

or, equivalently, like this:

MyClass foo = new MyClass();  // combined variable definition and assignment

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:

MyClass foo, bar;      // define two reference variables, foo and bar
foo = new MyClass();   // create a new object and assign a reference to it to foo
bar = foo;             // now foo and bar point to the same object

or even:

MyClass foo = new MyClass(), bar = foo;  // same, but shorter

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:

private MyClass getSomeObject() {
    // ...some code here...
}

you could call it and save the reference it returns into a variable like this:

MyClass foo;
foo = getSomeObject();

or like this:

MyClass foo = getSomeObject();

We can tell from the method declaration that getSomeObject() will always return a reference to a MyClass instance (or null), but not where that instance actually comes from. That depends entirely on what the code inside the getSomeObject() method does. The code might always create a new MyClass instance with new 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:

MyClass foo = new MyClass();  // create a new object and assign (a reference to) it to foo
foo = getSomeObject();        // forget the previous content of foo and replace it with whatever getSomeObject() returns

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:

new MyClass();       // create a new object and throw away(!) the reference to it
MyClass foo = getSomeObject();  // assign whatever getSomeObject() returns to foo

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 the MyClass 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.

呢古 2025-01-01 06:06:15

在 java 中,你总是必须使用 new 来实例化对象(嗯,几乎总是如此)。使用 getAssests() 您可以检索已创建的资产。我猜你的问题来自c++,其中new分配动态内存,但由于java只有动态对象,所以总是需要new。

In java you always have to use new to instantiate objects (well, almost always). With getAssests() you retrieve an already created one. I guess your question comes from c++ where new allocates dynamic memory, but since java has only dynamic objects, new is always needed.

请止步禁区 2025-01-01 06:06:15

当您调用函数的构造函数时,会使用 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.

太阳公公是暖光 2025-01-01 06:06:15

通过使用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.

半枫 2025-01-01 06:06:15

new 始终用于创建新对象。

AssetManager assetManager = getAssets();

只是将从方法 getAssets() 返回的值分配给引用 assetManager

[编辑]

我对 new 撒了谎,可以​​做这样的事情:

Foo.class.newInstance();

而且你也可以使用反射:

Foo.class.getDeclaredConstructors(Class[] parameterTypes).newInstance(arguments);

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);
年少掌心 2025-01-01 06:06:15

由于您用 [android] 标记了这一点,我猜测您的代码位于 ActivityService 内部。在本例中,getAssets() 是您要扩展的类的方法。因此,您实际上并没有创建它,而是要求现有代码为您提供对已存在内容的引用。

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.

葬花如无物 2025-01-01 06:06:15

请注意 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文