xhtml
 

Methods

A Book class should not just store information about a book. It should also gather together any operations needed on a book, as methods.

In this case, let's look at the price. We've stored it as an integer to make sure that arithmetic is done exactly, with no rounding errors. That is usually a good idea where money is concerned, because even a price like 5.10 can't be stored exactly using the double type. When we want to add up the prices of a collection of books, it is this integer that we will want. So, we will provide a method getPrice which returns this integer.

On the other hand, we will also want to print the price out, and then we will want a decimal point in it. Should we provide a method which prints out the price? No, because there is no way to know whether you want to print to System.out or to a file or into a graphical interface. So instead, we will provide a method showPrice which returns the price as a string with a decimal point in it. Here's version 2 of our book class, with the two price methods in it.

Book.java (version 2)

The showPrice method uses integer division to divide the price by 100 and throw away the remainder. It also uses the % operator to get the remainder.

We have added a getTitle method, which we are obviously going to need eventually.

We have also changed the main method to improve testing. It now takes a title and a price in as arguments, creates a book object from them, and then prints out its price.


Back