Java Reference
In-Depth Information
Sphere newBall = new Sphere(eightBall); // Create a copy of eightBall
The next section recaps what you have learned about methods and constructors with another example.
USING OBJECTS
You will create a program to do some simple 2D geometry. This gives you an opportunity to use more than
one class. You will define two classes, a class that represents point objects and a class that represents line
objects; you will then use these to find the point at which two lines intersect. You can put the files for the
example in a directory or folder with the name Try Geometry . Quite a few lines of code are involved, so
you will put it together piecemeal and get an understanding of how each piece works as you go.
TRY IT OUT: The Point Class
You first define a basic class for point objects:
import static java.lang.Math.sqrt;
class Point {
// Coordinates of the point
double x;
double y;
// Create a point from coordinates
Point(double xVal, double yVal) {
x = xVal;
y = yVal;
}
// Create a point from another Point object
Point(final Point oldPoint) {
x = oldPoint.x;
// Copy x coordinate
y = oldPoint.y;
// Copy y coordinate
}
// Move a point
void move(double xDelta, double yDelta) {
// Parameter values are increments to the current coordinates
x += xDelta;
y += yDelta;
}
// Calculate the distance to another point
double distance(final Point aPoint) {
return sqrt((x - aPoint.x)*(x - aPoint.x) + (y - aPoint.y)*(y -
Search WWH ::




Custom Search