Java Reference
In-Depth Information
type int . The Point class also has Point2D as a base, and the hierarchy of classes that represents points is
shown in Figure 19-6 .
FIGURE 19-6
The Point class actually predates the Point2D class, but the Point class was redefined to make it a sub-
class of Point2D when Point2D was introduced, hence the somewhat unusual class hierarchy with only two
of the subclasses as static nested classes. The merit of this arrangement is that all of the subclasses inherit
the methods defined in the Point2D class, so operations on each of the three kinds of point are the same.
Objects of all three concrete types that represent points can be passed around as references of type Point2D .
The three subclasses of Point2D define a default constructor that defines the point (0,0) and a constructor
that accepts a pair of coordinates of the type appropriate to the class type.
Each of the three concrete point classes inherits the following operations:
1. Accessing coordinate values: The getX() and getY() methods return the x and y coordinates of a
point as type double , regardless of how the coordinates are stored. These are abstract methods in the
Point2D class, so they are defined in each of the subclasses. Although you get coordinates as values
of type double from all three concrete classes via these methods, you can always access the coordin-
ates with their original type directly because the coordinates are stored in public fields with the same
names, x and y , in each case.
2. Calculating the distance between two points: You have no less than three overloaded versions
of the distance() method for calculating the distance between two points and returning it as type
double :
distance(double x1,double y1, double x2,double y2) : This is a static version of the meth-
od that calculates the distance between the points ( x1 , y1 ) and ( x2 , y2 ).
distance(double xNext,double yNext) : This calculates the distance from the current point
(the object for which the method is called) and the point ( xNext , yNext ).
distance(Point2D nextPoint) : This calculates the distance from the current point to the
point nextPoint . The argument can be any of the subclass types, Point , Point2D.Float , or
Point2D.Double .
Here's how you might calculate the distance between two points:
Point2D.Double p1 = new Point2D.Double(2.5, 3.5);
Point p2 = new Point(20, 30);
double lineLength = p1.distance(p2);
 
 
Search WWH ::




Custom Search