1

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).

asked Mar 16, 2013 at 23:55
1
  • What are the properties of your Account object? Commented Mar 16, 2013 at 23:57

3 Answers 3

4

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>();
}
answered Mar 16, 2013 at 23:58
Sign up to request clarification or add additional context in comments.

4 Comments

And if a Person owns several Accounts?
I think, the reverse is more compliant. Account objects should refer to Person
And for married people with a joined account?
@Aubin Married couples would simply share the same Account object in their respective ownedAccounts lists.
1

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;
answered Mar 17, 2013 at 0:01

Comments

0

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.

answered Mar 17, 2013 at 0:00

2 Comments

And if a Person owns several Accounts?
The question doesn't specify that. But if it did using a List<Account> and having an addAccount() method would make sense

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.