我有类 A 和 B,我想从类 B 中的类 A 访问方法,但它不起作用,我收到以下消息:
线程"main"中的异常 java.lang.NullPointerException
导致此问题的特定部分是在访问ba
时:
ba.getBalance() >= LIM
ba.debit(LIM);
我不确定我做错了什么,因为我已经创建了私有字段并在 main 中初始化了它。
B类:
public class B {
private A ba;
private long balance;
public B(long amount, A ba){
}
public boolean testCase(long amount){
//..
}
public long getBalance(){
return balance;
}
A类:
public class A {
private long balance;
public A(long amount){
}
public boolean debit(long amount){
//.. simple arithmetic
}
public long getBalance(){
return balance;
}
主要
A aa = new BankAccount(amount1); // where amounts are user input
B bb = new GoCardAccount(amount2, aa);
你忘记在构造函数中设置ba
public B(long amount, A ba){
balance = amount;
this.ba = ba;
}
在 B 构造函数中添加此行 这个.ba=ba .您没有为 A 分配任何值,因此它会抛出 NPE