What happens when you create a new object?

前端 未结 10 2361
梦谈多话
梦谈多话 2021-02-10 18:39

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

    The second picture is true. Each time you write new keyword following by constructor the new instance of class is created. Each time you write someVariable = ... the result of the expression from the right is assigned to the variable, i.e. the new reference is created.

    So,

    A a1 = new A(); // creates one object and assigns reference to a1
    A a2 = new A(); // creates another object and assigns reference to a2
    A a3 = a2; // just create yet another reference to previously created object 
    a1 = new A(); // creates new object and assigns its reference to the same variable that was previously used, so the previous object is "lost" now and can be garbage collected. 
    

提交回复
热议问题