Java Reference
In-Depth Information
CHAPTER
2
Understanding class definitions
Main concepts discussed in this chapter:
fields
constructors
parameters
methods (accessor, mutator)
assignment and conditional statement
Java constructs discussed in this chapter:
field, constructor, comment, parameter, assignment (=), block, return statement,
void , compound assignment operators (+=, −=), if statement
In this chapter, we take our first proper look at the source code of a class. We will discuss the ba-
sic elements of class definitions: fields , constructors, and methods. Methods contain statements,
and initially we look at methods containing only simple arithmetic and printing statements.
Later, we introduce conditional statements that allow choices between different actions to be
made within methods.
We shall start by examining a new project in a fair amount of detail. This project represents a
naïve implementation of an automated ticket machine. As we start by introducing the most basic
features of classes, we shall quickly find that this implementation is deficient in a number of
ways. So we shall then proceed to describe a more sophisticated version of the ticket machine that
represents a significant improvement. Finally, in order to reinforce the concepts introduced in this
chapter, we take a look at the internals of the lab-classes example encountered in Chapter 1.
2.1
Ticket machines
Train stations often provide ticket machines that print a ticket when a customer inserts the
correct money for their fare. In this chapter, we shall define a class that models something
like these ticket machines. As we shall be looking inside our first Java example classes, we
shall keep our simulation fairly simple to start with. That will give us the opportunity to ask
some questions about how these models differ from the real-world versions and how we
might change our classes to make the objects they create more like the real thing.
 
 
 
Search WWH ::




Custom Search