Java Reference
In-Depth Information
They include a user-chosen name for the field variable.
They end with a semicolon.
Remembering this pattern will help you when you write your own classes.
Indeed, as we look closely at the source code of different classes, you will see patterns such
as this one emerging over and over again. Part of the process of learning to program involves
looking out for such patterns and then using them in your own programs. That is one reason
why studying source code in detail is so useful at this stage.
2.4.2
Constructors
Constructors have a special role to fulfill. They are responsible for ensuring that an object is
set up properly when it is first created; in other words, for ensuring that an object is ready to be
used immediately following its creation. This construction process is also called initialization.
Concept:
Constructors
allow each object
to be set up prop-
erly when it is first
created.
In some respects, a constructor can be likened to a midwife: it is responsible for ensuring that
the new object comes into existence properly. Once an object has been created, the constructor
plays no further role in that object's life and cannot be called on it. Code 2.4 shows the con-
structor of the TicketMachine class.
One of the distinguishing features of constructors is that they have the same name as the class
in which they are defined— TicketMachine in this case. The constructor's name immediately
follows the word public , with nothing in between. 1
We should expect a close connection between what happens in the body of a constructor and in
the fields of the class. This is because one of the main roles of the constructor is to initialize the
Code 2.4
The constructor of the
TicketMachine
class
public class TicketMachine
{
Fields omitted.
/**
* Create a machine that issues tickets of the given price.
* Note that the price must be greater than zero, and there
* are no checks to ensure this.
*/
public TicketMachine( int cost)
{
price = cost;
balance = 0;
total = 0;
}
Methods omitted.
}
1
While this description is a slight simplification of the full Java rule, it fits the general rule we will use in
the majority of code in this topic.
 
Search WWH ::




Custom Search