I'm pretty new to Java, as my post might give away.
I need to create a class (let's call it class A) which uses another class (class B) as one of its fields. Class A's constructor calls class B's constructor. So far things work fine. But when one of A's methods tries to use one of B's methods on the object of class B, I get a NullPointerException. This is probably too confusing so I wrote this simple example which creates the Exception.
This is class B:
public class class_B {
private int y;
public class_B(int N) {
int y = N*N;
}
public int class_B_method() {
return y;
}
}
and this is class A:
public class class_A {
private class_B obj;
public class_A(int N) {
class_B obj = new class_B(N);
}
public int call_class_B_method() {
return obj.class_B_method();
}
public static void main(String[] args) {
int N =4;
class_A p = new class_A(N);
int a = p.call_class_B_method();
}
}
When I run class_A I get the exception on the line "int a = p.call_class_B_method();". I don't understand this, since 'obj' should have been created by the constructor 'class_B' and should be available for the method 'call_class_B_method'.
thanks!