When do instance variables get initialized and values assigned?

Posted by AKh on Stack Overflow See other posts from Stack Overflow or by AKh
Published on 2012-09-06T21:29:10Z Indexed on 2012/09/06 21:38 UTC
Read the original article Hit count: 276

When doees the instance variable get initialized? Is it after the constructor block is done or before it?

Consider this example:

public abstract class Parent {

 public Parent(){
   System.out.println("Parent Constructor");
   init();
 }

 public void init(){
   System.out.println("parent Init()");
 }
}

public class Child extends Parent {

private Integer attribute1;
private Integer attribute2 = null;

public Child(){
    super();
    System.out.println("Child Constructor");
}

public void init(){
    System.out.println("Child init()");
    super.init();
    attribute1 = new Integer(100);
    attribute2 = new Integer(200);
}

public void print(){
    System.out.println("attribute 1 : " +attribute1);
    System.out.println("attribute 2 : " +attribute2);
}
}

public class Tester {

public static void main(String[] args) {
    Parent c = new Child();
    ((Child)c).print();

}
}

OUTPUT:

Parent Constructor

Child init()

parent Init()

Child Constructor

attribute 1 : 100

attribute 2 : null


  1. When the memory for the atribute 1 & 2 are allocated in the heap ?

  2. Curious to know why is attribute 2 is NULL ?

  3. Are there any design flaws?

© Stack Overflow or respective owner

Related posts about java

Related posts about object