Bookstore Example #2 (with methods and code)

Class Diagram

Sample Code:,


Method Names

Note that the method names on the class diagram are very simple, usually just a verb. That's because the class itself usually supplies the noun: item.display(), customer.bill(). There's usually no reason to have methods like item.itemDisplay() or customer.customerBill(); they're redundant.

A special case arises when you want to extend a method of a superclass, as with Item.display(). For Book to override the superclass method, it _has_ to name it the same thing: Book.display(). That way, when clients call item.display(), they'll get the Book version if appropriate.

(Inside Book.display(), it is usually advisable to start the method with a call to Item.display(); you can do this with the special syntax "super.display()". This executes the superclass version of the method, then returns to continue the subclass code.)

Classes Not Shown

In thinking about how this system would work in the real world, there are two critical pieces not shown on the diagram: UI and data storage (database). This is actually deliberate. The classes shown here form the "business logic" of the application, which should remain the same no matter what kind of UI or data storage mechanism you choose. You don't have to show everything on one diagram.

Example Code and are examples of translating a design to Java code. They compile except for undefined references to the missing classes. has some examples of methods that provide controlled access to the customer object's data. Often these are just get/set pairs, but not always. The accessor methods aren't shown on the class diagram (although they could be). Often it's easiest to let them be implied by the variables shown on the diagram, unless you need to be very precise.

I like to name member variables starting with a leading underscore: _item, _address. This can help distinguish member variables from local variables and method parameter names. There are other ways of doing this as well.

A one-to-one or many-to-one relationship is often most easily expressed with a simple object reference, for example _shippingAddress. A one-to-many relationship usually needs some kind of collection of references, for example _itemOrders. A many-to-many relationship is difficult and best avoided if possible.