java Java中new关键字的作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16942289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Role of new keyword in Java
提问by Prateek Singla
I am not sure how new
keyword behaves in Java. Is it for sure that every time I will use new
keyword, a new Object will be created on heap?
我不确定new
关键字在 Java 中的行为。确定每次我使用new
关键字时,都会在堆上创建一个新对象吗?
I got this doubt when I was studying following example-
我在学习以下示例时遇到了这个疑问-
class Mixer {
Mixer() { }
Mixer(Mixer m) { m1 = m; }
Mixer m1;
public static void main(String[] args) {
Mixer m2 = new Mixer();
Mixer m3 = new Mixer(m2); // Does it create any new mixer object?
m3.go();
Mixer m4 = m3.m1; m4.go();
Mixer m5 = m2.m1; m5.go();
}
void go() { System.out.print("hi "); }
}
The line Mixer m3 = new Mixer(m2);
invokes a constructor which does not create any new object. So, is it that no new object was created?
该行Mixer m3 = new Mixer(m2);
调用不创建任何新对象的构造函数。那么,是不是没有创建新的对象呢?
Also, Which variable refers to which object in the end of program, i.e. till we get NullPointerExcetion
for variable m5
.
此外,哪个变量指的是程序末尾的哪个对象,即直到我们得到NullPointerExcetion
变量m5
。
采纳答案by Joeblade
new always creates a new instance (so always reserves heap memory, etc.).
new 总是创建一个新实例(所以总是保留堆内存等)。
This should illustrate it. note that == on an instance will tell you if it is the same instance (object) or a different one. (which is why you should always use equals, unless this is what you want to do)
这应该说明它。请注意,实例上的 == 会告诉您它是同一个实例(对象)还是不同的实例。(这就是为什么你应该总是使用 equals,除非这是你想要做的)
I've added a funny thing happening with strings. "abc" does not create a new instance, but reuses an existing one. but when you call new on the String class it does.
我在字符串中添加了一个有趣的事情。“abc”不会创建新实例,而是重用现有实例。但是当你在 String 类上调用 new 时,它确实如此。
public class Test {
private String value;
public String getValue() {
return value;
}
public Test() {
value = "default";
}
public Test(Test t) {
this.value = t.getValue();
}
public Test(String value) {
this.value = value;
}
public static void main(String[] argv) {
Test t1 = new Test();
Test t2 = new Test(t1);
if (t1 == t2) {
System.out.println("t1 == t2. should not happen");
} else {
System.out.println("t1 is a different instance from t2");
}
String s1 = "test";
String s2 = "test";
if (s1 == s2) {
System.out.println("s1 == s2. strings initialized with quotes don't always get a new instance.");
} else {
System.out.println("s1 is a different instance from s2. should not happen");
}
String s3 = new String("test");
String s4 = new String(s3);
if (s3 == s4) {
System.out.println("s3 == s4. should not happen.");
} else {
System.out.println("s3 is a different instance from s4, as they were newed.");
}
}
}
回答by Michael Berry
Yes - every time you use new
(as a keyword) a new object will be created. In this case:
是的 - 每次使用new
(作为关键字)时都会创建一个新对象。在这种情况下:
Mixer m3 = new Mixer(m2);
The line Mixer m3 = new Mixer(m2); invokes a constructor which does not create any new object.
Mixer m3 = new Mixer(m2); 调用不创建任何新对象的构造函数。
Your reasoning is completely incorrect. A new Mixer
is being created using m2
as a parameter. Usually this indicates a copy constructor - creating a new Mixer with the same properties as the old one (but it is always a new, distinct object, and doesn't technically haveto copy the properties of the object passed in at all.)
你的推理完全不正确。Mixer
正在创建一个新的m2
作为参数。这通常表明一个拷贝构造函数-创建一个新的调音台具有相同属性与旧(但它始终是一个新的,不同的对象,而在技术上不具有复制在所有传递的对象的属性。)
回答by Andy Thomas
From the programmer's perspective, new
causes the creation of a new object.
从程序员的角度来看,new
会导致新对象的创建。
However, the compiler may perform escape analysisto determine whether the object really needs to be created on the heap at runtime.
但是,编译器可能会执行逃逸分析,以确定是否真的需要在运行时在堆上创建对象。
For your last question, your code creates two objects. One is referenced by m2, m3.m1 and m4, and the other is referenced by m3.
对于您的最后一个问题,您的代码创建了两个对象。一个由m2、m3.m1和m4引用,另一个由m3引用。
回答by a CVn
First, forget about the stack/heap distinction - that is an implementation detail of the compiler or the runtime (depending on the language in question). It might make a difference if you are doing systems programming in C or assembly, but not when you are working in garbage-collected languages and environments like Java or .NET.
首先,忘记堆栈/堆的区别——这是编译器或运行时的实现细节(取决于所讨论的语言)。如果您使用 C 或汇编语言进行系统编程,这可能会有所不同,但当您使用垃圾收集语言和环境(如 Java 或 .NET)工作时则不然。
And to answer your question: new
actually does two things in most(?) (all?) languages that has such an operator. It first allocates memory somewhere to hold an instance of the type, and then calls a constructor to initialize an instance of the type in that newly allocated memory. Constructor chaining then may cause other constructors to be called (either on the same type, base classes/superclasses of the type, or anything that type's constructor needs to do its work).
并回答您的问题:new
实际上在大多数(?)(所有?)具有此类运算符的语言中做了两件事。它首先在某处分配内存以保存该类型的实例,然后调用构造函数在新分配的内存中初始化该类型的实例。构造函数链接可能会导致其他构造函数被调用(相同类型、该类型的基类/超类,或者该类型的构造函数需要完成其工作的任何内容)。
As pointed out by @berry120, a constructor taking a parameter of the same type as the type that the constructor is for usually indicatesa copy constructor. Another way of achieving the same result is to have and make an explicit call to something like a clone()
method which returns a copy of the object it is called on.
正如@berry120所指出的,采用与构造函数所针对的类型相同类型的参数的构造函数通常表示复制构造函数。实现相同结果的另一种方法是对类似clone()
方法进行显式调用,该方法返回调用它的对象的副本。
回答by Niklas R
It does create a new object, and its constructor gets passed a reference to another object m2
that you have already created.
它确实创建了一个新对象,并且它的构造函数传递了一个对m2
您已经创建的另一个对象的引用。