質問

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();
役に立ちましたか?

解決 2

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.

他のヒント

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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top