0

I have classes A and B, I want to access a method from class A in class B but it isn't working, I'm getting the following message:

Exception in thread "main" java.lang.NullPointerException

The particular part that is causing this is when accessing ba:

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

I'm not sure what I'm doing wrong as I've created the private field and initialised it within main.

Class 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;
    }

Class A:

public class A {

     private long balance;

     public A(long amount){
    }

    public boolean debit(long amount){
        //.. simple arithmetic 
    }

    public long getBalance(){
        return balance;
    }

Main

A aa = new BankAccount(amount1); // where amounts are user input
B bb = new GoCardAccount(amount2, aa);
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Kaskader
  • 35
  • 1
  • 5
  • 1
    You need to assign the instance of `ba` you are passing to `B` constructor to your private field member `ba`, as you do for `amount`: `public B(long amount, A ba) { this.ba = ba; this.balance = amount }` – Alexandre Dupriez Aug 10 '17 at 10:01

2 Answers2

0

you forget to set ba in the constructor

    public B(long amount, A ba){
        balance = amount;
        this.ba = ba;
    }
Ali Faris
  • 17,754
  • 10
  • 45
  • 70
0

Add this line in B constructor this.ba=ba . You are not assigning any value to A , so it throws NPE

Ahi
  • 175
  • 1
  • 13