You saw in the previous chapter the class definition of a very
simple, generic class.
Here we show another example of a class but with more of the features
typically found in a class.
These members of a class include
- Data Fields - declare the data values
belonging to the class or object
- Constructors - special functions
called when an object is created to carry out initialization tasks.
- Methods - functions to carry out
tasks for the objects.
- Member Classes
- an inner class be defined within a class.We discuss these
in Chapter 7.
The class GenericClass
below illustrates these class features:
public
class
GenericClass
{
int i;
public GenericClass
(int k)
{
i = k;
}
public void set
(int j)
{
i = j;
}
public int get
()
{
return
i;
}
}
|
This field declares the property "i" as an integer
type. (By default its value will be 0.) It will be visible,
or in the scope of, to all the methods in the class.
A constructor is called when an instance of this class is
first created.
You
can use it to initialize properties.
This method passes a value for i. The variable j is a local
variable and only viable within this method.
This method returns the value in i.
|
Note: If
you are new to the concepts of object oriented programming,
it can be a steep jump from the class description code to a
clear mental image of what is going on. See Chapter
3: Supplements for futher introductory material on classes
and objects.
We see that this class declares a data field and has a constructor
to initialized that data and methods that act upon that data. We
can now use our new data type as in, for example:
void
aMethodSomewhere () {
//
Ceate an instance of this class type.
GenericClass a = new GenericClass(5);
int k = a.get ();
....
In the following pages we discuss in more detail the members of
a class definition, beginning with Data Fields.
Then we will present several demonstration programs to illustrate
the different aspects of class definition.
Latest update: Oct. 16, 2004
|