2017-08-10 58 views
0

我有类A和B,我要访问从A类的方法在B类,但它不工作,我得到了以下信息:的Java访问方法

异常在线程“主要”显示java.lang.NullPointerException

,是造成这种情况的特定部分被访问时ba

ba.getBalance() >= LIM   
ba.debit(LIM); 

我不知道我是d因为我创建了私有字段并在main中初始化了它。乙

类:

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); 
+1

您需要将传递给'B'构造函数的'ba'实例分配给您的专用成员'ba',就像您为'amount'所做的那样: 'public B(long amount,A ba){this.ba = ba; this.balance = amount}' –

回答

0

你忘记设置ba在构造

public B(long amount, A ba){ 
     balance = amount; 
     this.ba = ba; 
    } 
0

在乙构造 this.ba = BA添加此行。您没有为A分配任何值,因此它会抛出NPE