Java Reference
In-Depth Information
Our CowboyHat class also has five methods, so you can do five different things with a CowboyHat object.
One of these is a special method called a constructor , which creates a CowboyHat object — this is the meth-
od with the name, CowboyHat , that is the same as the class name. Constructors always have the same name
as the class. The items between the parentheses that follow the name of the constructor specify data that is
to be passed to the method when it is executed — that is, when a CowboyHat object is created.
WARNING Inpracticeyoumightneedtodefineafewothermethodsfortheclasstobeuseful;
you might want to compare CowboyHat objects for example, to see if one was larger than an-
other. However, at the moment you just need to get an idea of how the code looks. The details
are of no importance here, as you return to all this in Chapter 5.
Java Program Statements
As you saw in the CowboyHat class example, the code for each method in the class appears between braces,
and it consists of program statements . A semicolon terminates each program statement. A statement in Java
can spread over several lines if necessary because the end of each statement is determined by the semicolon,
not by the end of a line. Here is a Java program statement:
hatOn = false;
If you wanted to, you could also write this as
hatOn =
false;
You can generally include spaces and tabs, and spread your statements over multiple lines to enhance
readability if it is a particularly long statement, but sensible constraints apply. You can't put a space in the
middle of a name, for instance. If you write hat On , for example, the compiler reads this as two words.
Encapsulation
At this point we can introduce another bit of jargon you can use to impress or bore your friends — encap-
sulation . Encapsulation refers to the hiding of items of data and methods within an object. This is achieved
by specifying them as private in the definition of the class. In the CowboyHat class, the instance variables
owner , type , size , and hatOn were encapsulated. They were accessible only through the methods defined
for the class. Therefore, the only way to alter the values they contain is to call a method that does that. Being
able to encapsulate members of a class in this way is important for the security and integrity of class objects.
You may have a class with data members that can take on only particular values or values within a particular
range. The age of a person, for example, is generally greater than zero and less than 150, at least until med-
ical science extends the range. By hiding the data members and forcing the use of a method to set or change
the values, you can ensure that only legal values are set.
I mentioned earlier another major advantage of encapsulation — the ability to hide the implementation
of a class. By allowing only limited access to the members of a class, you have the freedom to change the
Search WWH ::




Custom Search