Java Reference
In-Depth Information
these classes and tests them. You should already have the Geometry directory set up if you followed my
suggestion with the previous example.
TRY IT OUT: Packaging Up the Line and Point Classes
The source and .class files for each class in the package must be in a directory with the name Geometry .
Remember that you need to ensure the path to the directory (or directories if you are storing .class files
separately) Geometry appears in the CLASSPATH environment variable setting before you try to compile
or use either of these two classes. You can best do this by specifying the -classpath option when you
run the compiler or the interpreter.
To include the class Point in the package, the code in is changed to:
package Geometry;
import static java.lang.Math.sqrt;
public class Point {
// Create a point from its coordinates
public Point(double xVal, double yVal) {
x = xVal;
y = yVal;
// Create a Point from an existing Point object
public Point(final Point aPoint) {
x = aPoint.x;
y = aPoint.y;
// Move a point
public void move(double xDelta, double yDelta) {
// Parameter values are increments to the current coordinates
x += xDelta;
y += yDelta;
// Calculate the distance to another point
public double distance(final Point aPoint) {
return sqrt((x - aPoint.x)*(x - aPoint.x)+(y - aPoint.y)*(y -
// Convert a point to a string
public String toString() {
return Double.toString(x) + ", " + y; // As "x, y"
Search WWH ::

Custom Search