Java Reference
In-Depth Information
Point start; // Start point of line
Point end; // End point of line
}
Here we have left the data members without an access attribute, so they are accessible from the Point
class, but not from classes outside the Geometry package.
How It Works
The package statement at the beginning of each source file defines the package to which the class
belongs. Remember, you still have to save it in the correct directory, Geometry . Without the public
attribute, the classes would not be available to classes outside the Geometry package.
Since we have declared the data members in the class Point as private , they will not be accessible
directly. We have added the methods getX() , getY() , setX() , and setY() to the Point class to
make the values accessible to any class that needs them.
The Line class hasn't been updated since our first example, so we first have to sort out the access
attributes. The two instance variables are declared as before, without any access attribute, so they can be
accessed from within the package but not from classes outside the package. This is an instance where
exposing the data members within the package is very convenient, and we can do it without exposing
the data members to any classes using the package. And we have updated the intersects() method
to reflect the changes in accessibility made to the members of the Point class.
We can now write the program that is going to import and use the package that we have just created.
Try It Out - Testing the Geometry Package
We can create a succession of points, and a line joining each pair of successive points in the sequence,
and then calculate the total line length.
import Geometry.*; // Import the Point and Line classes
public class TryPackage {
public static void main(String[] args) {
double[][] coords = { {1.0, 0.0}, {6.0, 0.0}, {6.0, 10.0},
{10.0,10.0}, {10.0, -14.0}, {8.0, -14.0}};
// Create an array of points and fill it with Point objects
Point[] points = new Point[coords.length];
for(int i = 0; i < coords.length; i++)
points[i] = new Point(coords[i][0],coords[i][1]);
// Create an array of lines and fill it using Point pairs
Line[] lines = new Line[points.length - 1];
double totalLength = 0.0; // Store total line length here
for(int i = 0; i < points.length - 1; i++) {
lines[i] = new Line(points[i], points[i+1]); // Create a Line
totalLength += lines[i].length(); // Add its length
System.out.println("Line "+(i+1)+' ' +lines[i] +
" Length is " + lines[i].length());
}
Search WWH ::




Custom Search