What happens when you create a new object?

前端 未结 10 1149
一个人的身影
一个人的身影 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:23

    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. 
    

提交回复
热议问题