So far, we have created a new book object by calling new Book()
and then setting the fields. Since the fields are private, that won't work
from any other class. So how are we going to create new books from other
classes?
One thing we could do is provide methods like setTitle and
setPrice. However, one of the aims of designing classes is to
make sure that they can't be misused. It would be bad to have titles or prices
of books changed by accident. What we can do is to insist that a title and
price can only be set from outside the Book class when a book
object is created, and not afterwords. In our bookshop program, if a new
edition or some new stock comes in, the program will have to create a new book
object. The old book object can be kept to represent the old stock, until it
is gone.
The call new Book() is a call to the default
constructor which constructs a new 'blank' object of the given class.
What we want to do is to provide a call new Book(title, price)
where we pass a title and price in to the contructor as the object is being
created. Here's how
Book.java (version 3)
Defining a constructor is like defining a method, except the name of the
method must be the same as the name of the class, and the method must have no
return type, not even void. When you define a constructor, the
default constructor is cancelled, so you can no longer create a 'blank'
book.