Hi,

I am new to Java and stuck at a problem. I have something like following-

package X
public abstract class A {
     A(int a) { this.a=p; }
     protected int p;
     abstract int func();
}
 
package Y
public class B extends A{
     B(int b) { super(b); }
     B() {}
     //p is accessible here
     int func() {
          D d=new D();
          d.func2();
    }   
 
    static void main() {
        func();
    }
}
 
public abstract class C extends B{
}
 
public class D extends C implements interface{
     int func2() {}
}

Now my problem is when I try to access p from func2(), I am getting a NullPointerException error. I am not initializing p anywhere through D()'s or B()'s no argument constructor. Is that the problem?
Any help would be very appreciated.

Thanks

Now my problem is when I try to access p from func2(), I am getting a NullPointerException error. I am not initializing p anywhere through D()'s or B()'s no argument constructor. Is that the problem?

Yes, in order to use p it must be initialised somewhere. Try this:

int func2()
{
  System.out.println( p ); // this should print "null" since p has not yet been initialised
  return p; // this should return null since p has not been initialised
}

However if you set p before calling func2() then your problem should be solved. I guess it depends on what you want to do.

This article has been dead for over six months. Start a new discussion instead.