Java Reference
In-Depth Information
in the outer wrapper of a class? Edit the source of the TicketMachine class to make the
change, and then close the editor window. Do you notice a change in the class diagram?
What error message do you get when you now press the Compile button? Do you think this
message clearly explains what is wrong?
Change the class back to how it was, and make sure that this clears the error when you com-
pile it.
Exercise 2.8 Check whether or not it is possible to leave out the word public from the
outer wrapper of the TicketMachine class.
Exercise 2.9 Put back the word public , and then check whether it is possible to leave out
the word class by trying to compile again. Make sure that both words are put back as they
were originally before continuing.
followed convention, we always start class names with an uppercase letter. As long as it is used
consistently, this convention allows class names to be easily distinguished from other sorts of
names, such as variable names and method names, which will be described shortly.
The words “public” and “class” are part of the Java language, whereas the word
“TicketMachine” is not—the person writing the class has chosen that particular name. We
call words like “public” and “class” keywords or reserved words - the terms are used fre-
quently and interchangeably. There are around 50 of these in Java, and you will soon get to
recognize most of them. A point worth remembering is that Java keywords never contain
uppercase letters, whereas the words we get to choose (like “TicketMachine”) are often a
mix of upper- and lowercase letters.
Fields, constructors, and methods
The inner part of the class is where we define the fields, constructors , and methods that give
the objects of that class their own particular characteristics and behavior. We can summarize
the essential features of those three components of a class as follows:
The fields store data persistently within an object.
The constructors are responsible for ensuring that an object is set up properly when it is first
The methods implement the behavior of an object; they provide its functionality.
In Java there are very few rules about the order in which you choose to define the fields, con-
structors, and methods within a class. In the TicketMachine class, we have chosen to list the
fields first, the constructors second, and finally the methods (Code 2.2). This is the order that
we shall follow in all of our examples. Other authors choose to adopt different styles, and this
Search WWH ::

Custom Search