Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

one to one relationship between classes in java

I have to implement following classes in Java SE but I cannot figure out that how can I achieve the one-to-one relationship between ATMCard and Account. I have researched (may be with wrong keywords) but could not find anything. Thank you in advance..

Class diagram, mentioned in the question

like image 510
Ken Vors Avatar asked Mar 03 '15 09:03

Ken Vors


1 Answers

First, I find your model a bit strange for ATMCard and Account:

  • isn't the PIN related to the ATMCard rather than to the Account?
  • isn't the custName related the Account ?

Then, the 1-1 relationship means you will have one of these:

  • the Account class has a member of type ATMCard
  • the ATMCard class has a member of type Account
  • both above relations.
  • none of the above, but getters that will fetch the related entity based on an ID. For instance, you can have a ATMCard$getAccount() that will retrieve the related Account based on the accountNo.

It really depends on the model logic you need.

As @NickHolt suggests, I would go for a one-way relation ship you can initialise through a factory, e.g.

public static ATMCard createCard(String name, int accNo, int pin, int initBal) {
   Account acc = new Account(name, accNo, initBal);
   ATMCard card = new ATMCard(pin);
   card.setAccount(acc);
   return card; 
}

You can have ATMCard and Account constructors protected to enforce the use of the public factory method.

Note: you can use a framework like Spring or Guice to provide this kind of factory and injection service.

like image 119
T.Gounelle Avatar answered Sep 29 '22 13:09

T.Gounelle