Wednesday 23 November 2016

who is responsible to allocate memory while creating objects in java ?

The answer is Object class.

We all know, in java, Object class is a super class of all user defined class. That means all the user defined class extends Object class by default.

And also we know whenever we are creating the sub class object, super class constructor will get called first, this is because in java, the object creation are done by using top down approach. That means, JVM allocates memory from parent class to sub class. The reason behind is, memory is allocated to sub class based on property inherited from parent and also based on its own property. 

So initially, Object class constructor will get execute first whenever you are creating object for all user defined class. If you look at the constructor of Object class.

public class Object {
     private transient Class<?> shadow$_klass_;
     public Object() {             //   constructor of Object class
        if (shadow$_klass_.isFinalizable()) {
              java.lang.ref.FinalizerReference.add(this);
        }
    }
}

The above code clearly explain the role of Object class, it is allocating memory for object in heap using native call and also add the object to FinalizeReference to make it available for garbage collection. After certain amount of time or cycle, GC will run and check the object of the reference still exist , if not it will remove from the heap memory.




If you like the above solution . Please share this blog

No comments:

Post a Comment

s