Saturday 15 February 2014

Object Creation and Destruction

In java Objects are stored in heap.

How to create an object
   Syntax
      new ClassName(parameters);
'new' keyword is used to create an object in Java. parameters are optional.

   Example
      new Person()

Creationof object is not sufficient to access the object methods and instance properties. There must be a reference to the object, to access the instance methods and properties of an object.

How to assign an object to a reference
   Syntax
      ClassName reference = new ClassName(parameters);

   Example
      Person p1 = new Person()

By using the reference p1, we can access the instance behaviors and properties of an object.

One object can be referred by more than one reference like below
Person p2 = p1;

Now p1 and p2 point to the same object. Here the reference count for the object is 2, since p1 and p2 are referring to the same object.

If reference count for an object is zero, then the object is eligible for garbage collection. I.e, the memory used by the object is freed and used for other purposes.

Remember, even if the objects is created inside a method, or block also, it always stored in the heap, only references stored on stack.

Detailed view of Object creation and Destruction
1. Lets say there is a class called Person, and an object created like below
      Person p1 = new Person()

object of the class Person is created in the heap and reference p1 refers to the newly created object


2. Assigning one more reference to the previously created object.
       Person p2 = p1;
As per the above statement references p1 and p2 refers to the same object.

Reference count is 2


3. Create one more object
     Person p3 = new Person()


4. To remove reference for an object, there are two ways. One way set null to the reference, or make the reference to point to other object.
     p2= null;

Above statement makes the reference variable p2 to set to null.

5. p2 = p3;
Now p2 refers to the object pointed by the reference p3




6. p2 = null;
p3 = null;

Now the object which is previously pointed by reference variables p2 and p3 has reference count zero. So it is eligible for garbage Collection.


You may like


Increase heap size                                                 Garbage Collection                                                 Home

No comments:

Post a Comment