Cover Data Structures and Algorithms with Object-Oriented Design Patterns in Java
next up previous contents index

Class Members: Fields and Methods

A class groups a set of values and a set of operations. The values and the operations of a class are called its members. Fields  implement the values and methods  implement the operations.

Suppose we wish to define a class to represent complex numbers . The Complex class definition shown in Program gif illustrates how this can be done. Two fields, real and imag, are declared. These represent the real and imaginary parts of a complex number (respectively). Program gif also defines two methods, setReal and setImag, which can be used to assign values to the real and imaginary parts of a complex number (respectively).

   program56420
Program: Complex class fields and methods.

Every object instance of the Complex class contains its own fields. Consider the following variable declarations:

Complex c = new Complex ();
Complex d = new Complex ();
Both c and d refer to distinct instances of the Complex class. Therefore, each of them has its own real and imag field. The fields of an object are accessed using the dot operator. For example, c.real refers to the real field of c and d.imag refers to the imag field of d.

Program gif also defines the methods setReal and setImag. In general, a method performs some operation on an instance of the class. Again, the dot operator is used to specify the object on which the operation is performed. For example, c.SetReal(1.0) invokes the setReal method on c and d.toString() invokes the toString method on d.


next up previous contents index

Bruno Copyright © 1998 by Bruno R. Preiss, P.Eng. All rights reserved.