Java Reference
In-Depth Information
but all objects of a class have the same types of data and all objects in a class have
the same methods. An object is usually referred to as an object of the class or as an
instance of the class
rather than as a value of the class, but it is a value of the class type.
To make this abstract discussion come alive, we need a sample definition.
instance
A Class Is a Type
If A is a class, then the phrases “bla is of type A,” “bla is an instance of the class A,” and
“bla is an object of the class A” all mean the same thing.
Display 4.1 contains a definition for a class named
DateFirstTry
and a program
that demonstrates using the class. Objects of this class represent dates such as
December 31, 2012 and July 4, 1776. This class is unrealistically simple, but it will
serve to introduce you to the syntax for a class definition. Each object of this class
has three pieces of data: a string for the month name, an integer for the day of the
month, and another integer for the year. The objects have only one method, which
is named
writeOutput
. Both the data items and the methods are sometimes called
members
of the object, because they belong to the object. The data items are also
sometimes called
fields
. We will call the data items
instance variables
and use the
term
method
instead of
member
.
The following three lines from the start of the class definition define three instance
variables (three data members):
member
field
instance
variable
public
String month;
public int
day;
public int
year;
//a four digit number.
The word
public
simply means that there are no restrictions on how these instance
variables are used. Each of these lines declares one instance variable name. You can
think of an object of the class as a complex item with instance variables inside of it.
So, an instance variable can be thought of as a smaller variable inside each object of the
class. In this case, the instance variables are called
month
,
day
, and
year
.
An object of a class is typically named by a variable of the class type. For example,
the program
DateFirstTryDemo
in Display 4.1 declares the two variables
date1
and
date2
to be of type
DateFirstTry
, as follows:
DateFirstTry date1, date2;
This gives us variables of the class
DateFirstTry
, but so far there are no objects of the
class. Objects are class values that are named by the variables. To obtain an object, you
must use the
new
operator to create a “new” object. For example, the following creates
an object of the class
DateFirstTry
and names it with the variable
date1
:
new
date1 =
new
DateFirstTry();