What happens when you create a new object?

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

    new A() will call the no param constructor of class A and will create a new memory object.

    A a1=new A();  // new memory object created
    
    A a2=new A(); // new memory object created
    
    A a3=new A(); // new memory object created
    

    There are three different objects that are getting created, so the SECOND picture is true.

    For the FIRST picture to be true, the declaration of references should be something like this:

    A a1=new A(); // new memory object created
    
    A a2=a1; // a2 points to the same memory object as a1 does
    
    A a3=a1; // a3 points to the same memory object as a1 does
    

    Here only one object(new used only once) is created but all the three references point to it.

提交回复
热议问题