简体   繁体   中英

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

问题中提到的类图

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, eg

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.

要在ATMCardAccount之间创建一对一关系,您必须在ATMCard类中创建Account实例。

The way I see this is ATM doesn't need to be related to ATMCard or the Account . Think about what happens you bank ATMCard is used in ATM of other bank? Or you bank doesn't allow the ATMCard be used in other bank ATM

These should part of withdrawal operation of the ATM.

You could have a bidirectional relationship from Account to ATMCard

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM