Java Reference
In-Depth Information
Let's take a look at an example of a complete class definition. The code for the class CowboyHat we
have been talking about might look like the following:
class CowboyHat
{
private String owner; //Name of current owner
private String type; //The type of hat
private int size; //Stores the hat size
private bool hatOn=false; //Records whether a hat is on or off
These specify the
attributes of the class
// Constructor to create a CowboyHat object
public CowboyHat(String anOwner, String aType, int aSize)
{
These braces enclose
the class definition
This is a special method
that creates
objects
size = aSize; //Set the hat size
type = aType; //Set the hat type
owner = anOwner; //Set the owner name
CowboyHat
}
// Method to put the hat on
public void putHatOn()
{
These braces enclose
the code for the
method putHatOn()
hatOn = true; // Record hat status as on
}
// Method to take the hat off
public void takeHatOff()
{
hatOn = false; // Record hat status as off
}
//Method to change the owner name
public void changeOwner(String newOwner)
{
These are the other
class methods
owner = newOwner;
}
// Method to get the hat size
public int getSize()
{
return size; // Return the size of the hat
}
}
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 will be .java to
identify that the file contains Java sourcecode.
The code for the class definition appears between the braces following the identification for the class, as
shown in the illustration. The code for each of the methods in the class also appears between braces.
The class has four instance variables, owner , type , size , and hatOn , and this last variable is always
initialized as false . Each object that is created according to this class specification will have its own
independent copy of each of these variables, so each object will have its own unique values for the
owner, the hat size, and whether the hat is on or off.
The keyword private , 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. Methods of a class can also be
specified as private . 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 program can only get access 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