I'm designing a class hierarchy for a Java Project. It involves creating a class hierarchy to represent several bank accounts. Now, all bank accounts have a few attributes in common. These can be moved to an abstract class. However, there is one attribute which is common to several of the bank accounts but not all of them. How should I implement this attribute in the class hierarchy? I probably shouldn't implement the attribute over and over in all the relevant classes but I can't think of another way to do it..
-
You can design an interface which binds a behavioral contract of Bank Accounts. Next, an Abstract class can contain the common behavior for all the bank accounts. You can then use the Decorator Pattern to embellish your classes to have specific behavior. There would be much required discussion, but here's the gist. Hope this helps. – Sid Apr 07 '13 at 16:18
-
I'm just starting OOP.. Some of that (like the 'decorator pattern') is a bit too complicated for me. – mahela007 Apr 07 '13 at 16:49
2 Answers
Let me try and help you out as much as possible.
You can have an interface IBankAccount, which defines the common behavior of the Bank Accounts. There will be just method definitions. E.g. A bank account should allow credit(), debit(), getBalance() etc. methods. It can have some additional methods not so common to all Bank Accounts.
Next you can have a BaseBankAccount class that would be abstract and implement these commmon methods. This is so because credit(), debit() and getBalance() will have a common behavior across bank accounts.
Then you can define a BankDecorator interface that will define BankAccount behaviors. Special Decorators will implement this interface to add extra features to the bank accounts. E.g. CurrentBankAccountDecorator will add the Current account functionality etc.
Hope this helps.

- 4,893
- 14
- 55
- 110
-
I'll have to read up a little bit about 'decorators' .. thanks for pointing me in the right direction. – mahela007 Apr 07 '13 at 18:08
-
This is not the only approach to your problem. I wish others reply with better solutions. There's much we can learn from each other. – Sid Apr 07 '13 at 18:11
You could use the programming concept of mixins.
See also: D. Ancona, G. Lagorio, and E. Zucca. Jam - designing a Java extension with mixins. ACM Trans. Program. Lang. Syst., 25(5):641-712, 2003.

- 2,542
- 2
- 23
- 35
-
Java doesn't seem to support this concept, according to the wikipedia page. – mahela007 Apr 07 '13 at 16:52
-
1It's right that Java does not natively support that concept. However, it is possible to create an own datastructure facilitating that. (I added a reference.) – nrainer Apr 07 '13 at 21:33