[英]Object Initialization - Java
I am new to Java. 我是Java新手。
I want to ask about object initialization. 我想问一下对象初始化。 First, I make a class.
首先,我上课。
public class A {
....
}
Then at the main class, the A class is instantiated. 然后在主类中实例化A类。
A a = new A();
Now, the question is, whether these two codes are the same? 现在的问题是,这两个代码是否相同?
A aa = a;
and 和
A aa = new A();
A aa = a
will make a reference to object a, however 将引用对象a,但是
A aa = new A();
will make a new object of type A. 将创建一个类型为A的新对象。
A a = new A();
A aa = a;
aa refers to the same object a. aa指的是同一对象。
A aa = new A();
about statement created new object of type A which is different from the a. 关于语句创建了一个不同于a的类型A的新对象。
No they are totally different! 不,他们是完全不一样的!
A aa = a;
Then aa
and a
refert to the same object in memory. 然后
aa
和对内存中相同对象a
引用。
A aa = new A();
Then aa is a new object. 那么aa是一个新对象。 And you have now two objects on the stack.
现在,您在堆栈上有两个对象。
No, they are different. 不,他们不同。 While
A aa = new A();
而
A aa = new A();
creates a new Object of type A, A aa = a;
创建一个新的A类型的对象,
A aa = a;
just passes the reference of a
to aa
, which means, those two point to the same Object. 只是传递的参考
a
至aa
,这意味着,这两个点对同一个对象。 You can verify this by printing the hashcode of a
and aa
. 您可以通过打印
a
和aa
的哈希码来验证这一点。
In the first case A aa = a;
在第一种情况下
A aa = a;
calling hashCode()
on both aa
and a
will yield the same result, since both point to the same Object. 在
aa
和a
上调用hashCode()
都会产生相同的结果,因为两者都指向同一个Object。
In your second case A aa = new A();
在第二种情况下
A aa = new A();
calling hashCode()
will yield different results, since you're creating a whole new instance of A
. 调用
hashCode()
会产生不同的结果,因为您正在创建A
全新实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.