Java Reference
In-Depth Information
Try It Out - The ListPoint Class
We can define the ListPoint class using the class Point with the code:
public class ListPoint {
// Constructor
public ListPoint(Point point) {
this.point = point; // Store point reference
next = null; // Set next ListPoint as null
}
// Set the pointer to the next ListPoint
public void setNext(ListPoint next) {
this.next = next; // Store the next ListPoint
}
// Get the next point in the list
public ListPoint getNext() {
return next; // Return the next ListPoint
}
// Return String representation
public String toString() {
return "(" + point + ")";
}
private ListPoint next; // Refers to next ListPoint in the list
private Point point; // The point for this list point
}
How It Works
A ListPoint object is a means of creating a list of Point objects that originate elsewhere so we don't need
to worry about duplicating Point objects stored in the list. We can just store the reference to the Point
object passed to the constructor in the data member, point . The data member, next , should contain a
reference to the next ListPoint in the list, and since that is not defined here, we set next to null .
The setNext() method will enable the next data member to be set for the existing last point in the
list, when a new point is added to the list. A reference to the new ListPoint object will be passed as
an argument to the method. The getNext() method enables the next point in the list to be
determined, so this method is the means by which we can iterate through the entire list.
By implementing the toString() method for the class, we enable the automatic creation of a String
representation for a ListPoint object when required. Here we differentiate the String representation of
our ListPoint object by enclosing the String representation of point between parentheses.
We could now have a first stab at implementing the PolyLine class.
Search WWH ::




Custom Search