简体   繁体   中英

Object Initialization - Java

I am new to 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 = 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 aa = new A();

will make a new object of type A.

A a = new A();
A aa = a;

aa refers to the same object a.

A aa = new A();

about statement created new object of type A which is different from the a.

No they are totally different!

A aa = a;

Then aa and a refert to the same object in memory.

A aa = new A();

Then aa is a new object. And you have now two objects on the stack.

No, they are different. While A aa = new A(); creates a new Object of type A, A aa = a; just passes the reference of a to aa , which means, those two point to the same Object. You can verify this by printing the hashcode of a and aa .

In the first case A aa = a; calling hashCode() on both aa and a will yield the same result, since both point to the same Object.

In your second case A aa = new A(); calling hashCode() will yield different results, since you're creating a whole new instance of A .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM