Java Reference
In-Depth Information
This code would be saved in a file with the name CowboyHat.java . The name of a file that contains the
definition of a class is always the same as the class name, and the extension is .java to identify that the file
contains Java source code.
The code that defines the class appears between the braces that follow the identification for the class, as
shown in Figure 1-7 . The code for each of the methods in the class also appears between braces. The class
has three instance variables, owner , size , and hatOn , and this last variable is always initialized as false .
Each object that is created according to this class specification has its own independent copy of each of these
variables, so each object has its own unique values for the owner, the hat size, and whether the hat is on or
off.
The private keyword, which has been applied to each instance variable, ensures that only code within
the methods of the class can access or change the values of these directly. The CowboyHat class methods are
public so they are accessible generally from outside the class. Methods of a class can also be specified as
private , which means they can only be invoked from methods inside the class.
Being able to prevent access to some members of a class from outside is an important facility. It protects
the internals of the class from being changed or used incorrectly. Someone using your class in another pro-
gram can get access only to the bits to which you want them to have access. This means that you can change
how the class works internally without affecting other programs that may use it. You can change any of the
things inside the class that you have designated as private , and you can even change the code inside any of
the public methods, as long as the method name and the number and types of values passed to it or returned
from it remain the same.
Search WWH ::




Custom Search