Reputation: 1393
I am confused as I am new to java, how many objects and references are created in the following piece of code?
MyClass t = new MyClass();
MyClass s = new MyClass();
MyClass v = s;
Please explain the answer:
2 Objects
3 References
Upvotes: 2
Views: 202
Reputation: 17525
Actually, your answer is wrong. It's the other way around:
2 objects (in the first two lines)
3 references (t, s, v, v and s share an object)
Upvotes: 0
Reputation: 3689
So you are creating a new object and storing a reference to that object in t
. The same for s
. Then you are assigning the s
reference to v
(not creating a new object). So you have three references and two objects.
Upvotes: 2
Reputation: 240860
2 Object and
3 reference
if you do new
you are creating object so there are two new so simply two Objects
and if you define
Foo a;// you have just created a reference
* Note: new
is only a way to create object, it can be created using otherways too
Upvotes: 2
Reputation: 272457
An object is an instance of a class, created with new
. You use new
twice, so there are two objects.*
A variable is, generally speaking, a reference.** So there are three references (t
, s
, v
), although two of them happen to refer to the same object.
MyClass
itself might create more objects internally.
** Except in the case of primitive types, like int
, float
, etc.
Upvotes: 2