Wednesday, March 26, 2008

Java Object Initialization

Suppose class A extends one class B and implements an interface C as follows:

public class A extends B implements C
{


}

In this case, if we call new A(), how object initialization will happen? Remember class A and B, and interface C are not empty


Whenever we instantiate A with a call new A(),

The JVM will allocate enough space in the heap to hold all the instance variables defined in class A, and its super class –B and the fields defined in interface C.
The JVM will initialize instance variables. First class B’s fields will be initialized. Then interface C’s declared fields will be initialized and in the end, Class A’s instance variables will be initialized.
The JVM will call method of class A. Whenever we compile a class, the java compiler creates an instance initialization method for each constructor declared in the source code of the class. It has a name, return type void and a set of parameters that matches the constructor parameters. So in our case class A will have an method and class B will have an method (assuming that there is only one constructor for each class). This method will be created for the constructor having call to super() (implicitly or explicitly) and will be call only once for new class creation and also we can be sure that the init method will be executed before the constructor code for that class is executed.


Case 1: there are only default constructors in class A and Class B



The method of class A will invoke the method of class B which in turn will call method of Object class (which is super class of all java objects). The method of Object class will do nothing and return back to class B’s method. Then the class B constructor will be executed and then returned back to class A method where class A constructor will be completely executed.


Case 2 : class B has multiple constructors defined.

For example

public class B
{
private int count;

public B()
{
this.B(100);

}

public B(int i)
{
count = i;
}
}

public Class A extends B
{



}

Here the method of class A will result in call to super() which is constructor B() which in turn calls this.B(). There will be only one method for class B that is for constructor B(int i).This method will call Object classes method. The method of Object class will do nothing and return back to class B’s method. Then the class B constructor B(int i) will be executed completing B() then returned back to class A method where class A constructor will be completely executed.

No comments: