What happens when you create a new object?

前端 未结 10 1164
一个人的身影
一个人的身影 2021-02-10 18:53

Ok, so what happens when you do this.

A a1=new A();

A a2=new A();

A a3=new A();

I upload two pictures on how I imagine it being like. Can you

10条回答
  •  南笙
    南笙 (楼主)
    2021-02-10 19:07

    No, the second picture is true. Because each time you create a new object with a separate reference, it becomes a separate pointer to a separate instance in memory.

    A a1 = new A(); // a new instance of A is created in memory and can be referenced by a1.
    A a2 = new A();
    

    Even though a1 and a2 are of the same type, it does not mean that they point to, or reference, the same object instance in memory.

    But, if a1 = a2; is ever executed, now, both a1 and a2 reference or point to the same A object instance in memory.

提交回复
热议问题