O'Reilly logo

Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition by Ivor Horton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

5.7. Using Objects

You'll create a program to do some simple 2D geometry. This will give you an opportunity to use more than one class. You'll define two classes, a class that represents point objects and a class that represents line objects; you'll then use these to find the point at which two lines intersect. Call the example TryGeometry, so this will be the name of the directory or folder in which you should save the program files. Quite a few lines of code are involved, so you'll 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 - aPoint.y));
  }

  // Convert a point to a string
  public String toString() {
    return Double.toString(x) + ", " + y;    // As "x, y"
  }
}

You should save this as Point.java in the directory TryGeometry.

5.7.1.

5.7.1.1. How ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required