This is probably a silly questions but its something I am trying to understand. I have 2 classes: a Person class and an Account class. In the Account class I have a 3 methods to set an account balance, to withdraw from that balance, and to return that balance. If I created a new object for a new Person and a new Account how do I tie them together? By together I mean how do I know when I try and get the the account balance, that I am getting it for a specific person and not just anyones balance? (assuming I have multiple account and person objects).
3 Answers 3
You connect them together by placing the Account (Wouldn't be a mistake to make it a Array of Accounts) object into the Person object. and then access the appropriate account using the Person:
class Person
{
String name;
String id;
...
List<Account> ownedAccounts = new ArrayList<Account>();
}
4 Comments
ownedAccounts lists.You can add field in Person class for instance:
ArrayList<Account> accounts;
or you can add some field in Account class (if only one person can be owner otherwise you will also need some list or set):
Person person;
Comments
The way that makes sense to me is to have an account object reference in the Person class.
class Person { Account account; }
and then you can add a checkAccount method to the person class.
void checkBalance(){ return account.getBalance(); }
Then wherever you have a Person object you can call
person.checkBalance();
To make sure that the account is that person's you should pass the Account object in the constructor of the Person object.
Person(Account account){ this.account = account }
Or you could have a setter method. If every person in the system must have an account then passing it in the constructor is a better idea.
Accountobject?