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

why don't you post code that actually compiles?

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.