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
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
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.
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
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.
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)