Dilshad Abduwali
Dilshad Abduwali

Reputation: 1458

How do I access the other Object in Java?

I have two classes one Customer and Account. In the Customer class I have the name of the customer and the accounts he has. The accounts are in a array:

private Account accounts[] = new Account[2];

In the beginning of the program the savings account will be set up:

public Customer(){
    account[0] = new Account("savings"); 
}

where the constructor of the Account class is:

public Account(String name){
     this.name = name;
}

and I have a method in Customer to add a credit account:

private void addAccount(){
    account[1] = new Account("credit");
}

and now a I have to transfer money from savings to credit in Account class

How do I access the two different accounts in Customer class. I have tried but failed with NullpointerExceptions

Thank you.

Upvotes: 0

Views: 78

Answers (2)

vikingsteve
vikingsteve

Reputation: 40408

Your method could look like this:

// addAccount method must already have been called!
private void transferFromSavingsToCredit(double amount) {
    accounts[0].balance -= amount;
    accounts[1].balance += amount;
}

Upvotes: 1

Nargis
Nargis

Reputation: 4787

In your Account class:

You should have a field call Balance that tracks the amount you have in that Account.

Then In your Customer Class :

You should have a method called transfer(Account A, Account B,int amount) then in this Class you should have logic in which if money is transferred from Account A to Account B , you shall subtract amount from Account A balance and add it to Account B balance.

Upvotes: 1

Related Questions