Java Reference
In-Depth Information
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.
and a program
that demonstrates using the class. Objects of this class represent dates such as
December 31, 2007 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
Display 4.1 contains a definition for a class named
DateFirstTry
. Both the data items and the methods are sometimes called
writeOutput
member
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 call the
field
methods
methods.
instance
variable
The following three lines from the start of the class definition define three instance
variables (three data members):
public String month;
public int day;
public int year; //a four digit number.
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
The word
public
.
An object of a class is typically named by a variable of the class type. For example,
the program
,
, and
month
day
year
in Display 4.1 declares the two variables
and
DateFirstTryDemo
date1
to be of type
, as follows:
date2
DateFirstTry
DateFirstTry date1, date2;
This gives us variables of the class
, 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
DateFirstTry
operator to create a “new” object. For example, the following creates
an object of the class
new
new
and names it with the variable
:
DateFirstTry
date1
date1 = new DateFirstTry();
Search WWH ::




Custom Search