Java Reference
In-Depth Information
inside the object. As you recall, they use different call syntax than static methods:
You write the object's name, then a dot, and then the method's name and parameters.
Each object's methods are able to interact with the data stored inside that object.
The preceding client program translates the position of two Point objects. It does
this by manually adjusting their x and y values:
p1.x += 11; // client code translating a Point
p1.y += 6;
Since translating points is a common operation, we should represent it as a
method. One option would be to write a static translate method in the client code
that accepts a Point , a delta- x , and a delta- y as parameters. Its code would look like
the following:
// a static method to translate a Point;
// not a good choice in this case
public static void translate(Point p, int dx, int dy) {
p.x += dx;
p.y += dy;
}
A call to the static method would look like the following line of code:
translate(p1, 11, 6); // calling a translate static method
However, a static method isn't the best way to implement the behavior. The Point
class is supposed to be reusable so that many client programs can use it. If the
translate method is placed into our PointMain client, other clients won't be able
to use it without copying and pasting its code redundantly. Also, one of the biggest
benefits of programming with objects is that we can put related data and behavior
together. The ability of a Point to translate data is closely related to that Point
object's ( x, y ) data, so it is better to specify that each Point object will know how to
translate itself. We'll do this by writing an instance method in the Point class.
We know from experience with objects that you can call an instance method called
translate using “dot notation”:
p1.translate(11, 6); // calling a translate instance method
Notice that the instance method needs just two parameters: dx and dy . The client
doesn't pass the Point as a parameter, because the call begins by indicating which
Point object it wants to translate ( p1 ). In our example, the client is sending a
translate message to the object to which p1 refers.
Instance method headers do not have the static keyword found in static method
headers, but they still include the public keyword, the method's return type, its name,
 
Search WWH ::




Custom Search