Java Reference
In-Depth Information
The (non- static ) methods of a class are called the instance methods of the class.
In the definition of the class Clock , all the data members are private and all the
method members are public . However, a method can also be private . For example,
if a method is only used to support other methods of the class, and the user of the
class does not need to access this method, you make it private .
Notice that we have not yet written the definitions of the methods of the class Clock .
(You will learn how to write them in the section Definitions of the Constructors
and Methods of the class Clock .) Also notice that the method equals has only
one parameter, although you need two things to make a comparison. Similarly, the method
makeCopy has only one parameter. An example later in this chapter will help explain why.
Before giving the definition of the class Clock , we first introduce another important
concept related to classes—constructors.
Constructors
In addition to the methods necessary to implement operations, every class can have special
types of methods called constructors. A constructor has the same name as the class, and
it executes automatically when an object of that class is created. Constructors are used to
guarantee that the instance variables of the class are initialized.
There are two types of constructors: those with parameters and those without parameters.
The constructor without parameters is called the default constructor.
Constructors have the following properties:
￿ The name of a constructor is the same as the name of the class.
￿ A constructor, even though it is a method, has no return type. That is, it
is neither a value-returning method nor a void method.
￿ A class can have more than one constructor. However, all constructors of a
class have the same name. That is, the constructors of a class can be overloaded.
￿ If a class has more than one constructor, the constructors must have
different signatures.
￿ Constructors execute automatically when class objects are instantiated.
Because they have no types, they cannot be called like other methods.
￿ If there are multiple constructors, the constructor that executes depends on the
type of values passed to the class object when the class object is instantiated.
For the class Clock , we will include two constructors: the default constructor and a
constructor with parameters. The default constructor initializes the instance variables used
to store the hours, minutes, and seconds, each to 0 . Similarly, the constructor with
parameters initializes the instance variables to the values specified by the user. We will
illustrate shortly how constructors are invoked.
8
 
 
 
Search WWH ::




Custom Search