Java Reference
In-Depth Information
1.8. Methods and Parameters
Objects of the previously defined Point class are exposed to manipulation
by any code that has a reference to a Point object, because its fields
are declared public . The Point class is an example of the simplest kind
of class. Indeed, some classes are this simple. They are designed to fit
purely internal needs for a package (a group of cooperating classes) or
to provide simple data containers when those are all you need.
The real benefits of object orientation, however, come from hiding the
implementation of a class behind operations performed on its data. Oper-
ations of a class are declared via its methods instructions that operate on
an object's data to obtain results. Methods access internal implement-
ation details that are otherwise hidden from other objects. Hiding data
behind methods so that it is inaccessible to other objects is the funda-
mental basis of data encapsulation.
If we enhance the Point class with a simple clear method (to clear, or
reset the coordinates to zero), it might look like this:
public void clear() {
x = 0.0;
y = 0.0;
}
The clear method has no parameters, hence the empty () pair after its
name; clear is declared void because it does not return any value. Inside
a method, fields and other methods of the class can be named directlywe
can simply say x and y without an explicit object reference.
1.8.1. Invoking a Method
Objects in general do not operate directly on the data of other objects,
although, as you saw in the Point class, a class can make its fields pub-
 
Search WWH ::




Custom Search