xhtml
 

First Class

Suppose a program is needed to keep stock of the books in a bookshop. This is going to be a fairly big program, so we need to start small and solve a bit of the problem first, before tackling the rest. So, let's start with the idea of a book.

Let's have a class in a file called Book.java, and use it to create several book objects when the program runs. The first thing to do is to decide what information needs to be stored about a book. We will just store the title and the price (though in real life, there would also be the author and the ISBN, at least). Here's our first stab at a Java class:

Book.java (version 1)

This has exactly the same structure as the programs we have been writing. In fact, it is a program. The main new features are:

A class is usually declared as public, because it needs to be accessible by the other classes making up the program. The object variables should always be declared as private, unless you have a very good reason not to, so we have started as we mean to go on. It is also a good idea to get into the habit of putting a main method in all your major classes, for testing. (Minor classes will get tested by being used from the major classes.)


Back