This discussion is archived
4 Replies Latest reply: Jul 31, 2010 8:28 AM by 843798 RSS

Sub-class fields are null when Super-class constructor is called?

843798 Newbie
Currently Being Moderated
Hi,

I have a class B that extends from class A. The constructor of class B calles the super constructor of class A. The constructor of class A uses reflection to change the value of an object in class B. However when the constructor of A is called, even though the field in class B (named 'c') is already initialised (C c = new C()), I still get a null pointer exception that field 'c' in B is not initialised.

At first I thought this is because the constructor of class A is called before the construcot of class B. However in the code it is clear that the constructor of class A is called FROM the constructor of class B.
public void B(){ 
   super();
}{code}
Does anyone know if this is normal and why this happens? I have attached all the code to replicate the problem;{code:java}import java.lang.reflect.Field;

public class A {

     public A() {

          try{
               Field field = this.getClass().getField("c");
               if(field != null){
                    Object object = field.get(this);
                    ((C)object).value = 1;
               }
          }
          catch(Exception e){
               e.printStackTrace();
          }
     }

}

public class B extends A {

     public C c = new C();

     public B(){
          super();
          System.out.println(c.value);
     }     

     public static void main(String[] args){new B();}
}

public class C {

     public int value = 0;

}
{code}Main method is in class B. 

Regards,
Sim085

Edited by: sim085 on 31-Jul-2010 13:01

Edited by: sim085 on 31-Jul-2010 13:01