Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when you create a new object?

Tags:

java

object

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 tell me what picture is true?

First picture: enter image description here

Second picture: enter image description here

I always thought the first picture is true, but now I don't really know, and I suspect the second to be true.

Also, can you explain to me what each side does? Like, what does "A a1" do and what does "new A()" do?

Thanks.

like image 813
ABCD123 Avatar asked Nov 29 '22 00:11

ABCD123


2 Answers

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.

like image 171
Juned Ahsan Avatar answered Dec 06 '22 16:12

Juned Ahsan


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.

like image 30
blackpanther Avatar answered Dec 06 '22 14:12

blackpanther