Pages

Monday 9 July 2012

Objects and Reference Variables


Shape rectangle, circle;
rectangle = new Shape();
Shape circle = new Shape();

Shape is class. How many objects and reference variable is created by the above code ?

Solution : Two objects and three reference variables are created. When a reference variable is created, it means a variable is created whether a reference value is assigned or not.

Rules to keep in mind when dealing with Java:
  1. Variables are not objects. Variables contain objects (or null) -- a particular object can be stored in zero or more variables simultaneously. This does not create new objects, see #3.
  2. Mutating an object mutates that object.
  3. Assigning (or passing) an object does not make a copy/clone/duplicate.

References :
  1. http://stackoverflow.com/questions/6499636/java-objects-reference-variables-and-the-garbage-collection-heap

No comments:

Post a Comment