Main Page

Previous Next

Using Objects

Let's create an example to do some simple 2D geometry. This will give us an opportunity to use more than one class. We will define two classes, a class of point objects and a class of line objects - we then use these to find the point at which the lines intersect. We will 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 we will put it together piecemeal, and try to understand how each piece works as we go.

Try It Out - The Point Class

We first define a basic class for point objects:

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 Math.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 in the directory TryGeometry.

How It Works

This is a simple class that has just two instance variables, x and y, which are the coordinates of the Point object. At the moment we have two constructors. One will create a point from a coordinate pair passed as arguments, and the other will create a new Point object from an existing one.

There are three methods included in the class. First we have the move()method that moves a Point to another position by adding an increment to each of the coordinates. We also have the distance() method that calculates the distance from the current Point object to the Point object passed as an argument. This uses the Pythagorean theorem to compute the distance as shown below.

Finally we have a method toString() that returns a string representation of the coordinates of the current point. If a class defines the toString() method, an object of that class can be used as an operand of the string concatenation operator +, so you can implement this in any of your classes to allow objects to be used in this way. The compiler will automatically insert a call to toString() when necessary. For example, suppose thePoint is an object of type Point, and we write the statement:

System.out.println("The point is at " + thePoint);

The toString() method will be automatically invoked to convert thePoint to a String, and the result will be appended to the String literal. We have specified the toString() method as public, as this is essential here for the class to compile. We will defer explanations as to why this is so until later in this chapter.

Note how we use the static toString() method defined in the class Double to convert the x value to a String. The compiler will insert a call to the same method automatically for the y value as the left operand of the + operation is a String object. Note that we could equally well have used the valueOf() method in the String class. In this case the statement would be written like this:

    return String.valueOf(x) + ", " + y;    // As "x, y"

Try It Out - The Line Class

We can use Point objects in the definition of the class Line:

class Line {
  Point start;   // Start point of line
  Point end;     // End point of line

  // Create a line from two points
  Line(final Point start, final Point end) {
    this.start = new Point(start);
    this.end = new Point(end);

  // Create a line from two coordinate pairs
  Line(double xStart, double yStart, double xEnd, double yEnd) {
    start = new Point(xStart, yStart);   // Create the start point
    end = new Point(xEnd, yEnd);         // Create the end point

  // Calculate the length of a line
  double length() {
    return start.distance(end);  // Use the method from the Point class

  // Convert a line to a string 
  public String toString() {
    return "(" + start+ "):(" + end + ")";    // As "(start):(end)"
  }                                           // that is, "(x1, y1):(x2, y2)"

You should save this as in the directory TryGeometry.

How It Works

You shouldn't have any difficulty with this class definition, as it is very straightforward. The class Line stores two Point objects as instance variables. There are two constructors for Line objects, one accepting two Point objects as arguments, the other accepting the (x, y) coordinates of the start and end points. You can see how we use the variable this to differentiate the class instance variables, start and end, from the parameter names in the constructor.

Note how the constructor that accepts Point objects works:

  // Create a line from two points
  Line(final Point start, final Point end) {
    this.start = new Point(start);
    this.end = new Point(end);

With this implementation of the constructor, two new Point objects are created which will be identical to, but independent of, the objects passed to the constructor. If you don't think about what happens you might be tempted to write it as:

  // Create a line from two points
  Line(final Point start, final Point end) {
    this.start = start;              // Dependent on external object!!!
    this.end = end;                  // Dependent on external object!!!

The important thing you should notice here, is that the way the constructor is implemented could cause problems that might be hard to track down. It's the same problem of an object variable being separate from the object to which it refers. In this version of the constructor no new points are created. The start and end members of the object refer to the Point objects passed as arguments. The Line object will be implicitly dependent on the Point objects that are used to define it. If these were changed outside the Line class, by using the move() method for example, this would 'silently' modify the Line object. You might consciously decide that this is what you want, so the Line object continues to be dependent on its associated Point objects, for instance in a drawing package. But, in general, you should avoid implicit dependencies between objects.

In the toString()method for the Line class, we are able to use the Point objects directly in the formation of the String representation of a Line object. This works because the Point class also defines a toString() method.

We've now defined two classes. In these class definitions, we've included the basic data that defines an object of each class. We've also defined some methods which we think will be useful, and added constructors for a variety of input parameters. Note how the Point class is used in the definition of the Line class. It is quite natural to define a line in terms of two Point objects, and the Line class is much simpler and more understandable than if it was defined entirely in terms of the individual x and y coordinates. To further demonstrate how classes can interact, and how you can solve problems directly, in terms of the objects involved, let's devise a method to calculate the intersection of two Line objects.

Creating a Point from Two Lines

We could add this method to the Line class. The diagram below illustrates how the mathematics works out.

Click To expand

You can ignore the mathematics if you want to, as it is not the most important aspect of the example. If you are willing to take the code in the new constructor on trust, then skip to the Try It Out section below. On the other hand you shouldn't find it too difficult if you can still remember what you did in high school.


One way to get the intersection of two lines is to use equations like those shown. These are called parametric equations because they use a parameter value (s or t) as the variable for determining points on each line. The parameters s and t vary between 0 and 1 to give points on the lines between the defined start and end points. When a parameter s or t is 0 the equations give the coordinates of the start point of each line, and when the parameter value is 1 you get the end point of the line.

Where the lines intersect, the equations for the lines must produce the same (x, y) values, so, at this point, the right-hand sides of the equations for x for the two lines must be equal, and the same goes for the equations for y. This will give you two equations in s and t, and with a bit of algebraic juggling you can eliminate s to get the equation shown for t. You can then replace t in the equations defining line 1 to get x and y for the intersection point.

Try It Out - Calculating the Intersection of Two Lines

We can use these results to write the additional method we need for the Line class. Add the following code to the definition in

// Return a point as the intersection of two lines -- called from a Line object
Point intersects(final Line line1) {
  Point localPoint = new Point(0, 0);

  double num = (this.end.y - this.start.y)*(this.start.x - line1.start.x) -
               (this.end.x - this.start.x)*(this.start.y - line1.start.y);

  double denom = (this.end.y - this.start.y)*(line1.end.x - line1.start.x) -
                 (this.end.x - this.start.x)*(line1.end.y - line1.start.y);

  localPoint.x = line1.start.x + (line1.end.x - line1.start.x)*num/denom;
  localPoint.y = line1.start.y + (line1.end.y - line1.start.y)*num/denom;

  return localPoint;

Since the Line class definition refers to the Point class, the Line class can't be compiled without the other being available. When you compile the Line class the compiler will compile the other class too.

How It Works

The intersects()method is called from one Line object, and takes another Line object as an argument. In the code, the local variables num and denom are the numerator and denominator in the expression for t in the diagram. We then use these values to calculate the x and y coordinates for the intersection.


If the lines are parallel, the denominator in the equation for t will be zero, something you should really check for in the code. For the moment, we will ignore it and end up with coordinates that are Infinity if it occurs.

Note how we get at the values of the coordinates for the Point objects defining the lines. The dot notation for referring to a member of an object is just repeated when you want to reference a member of a member. For example, for the object line1, the expression line1.start refers to the Point object at the beginning of the line. Therefore line1.start.x refers to its x coordinate, and line1.start.y accesses its y coordinate.

Now we have a Line class, which we can use to calculate the intersection point of two Line objects. We need a program to test the code out.

Try It Out - The TryGeometry Class

We can demonstrate the two classes we have defined, with the following code in the method main():

public class TryGeometry {
  public static void main(String[] args) {
    // Create two points and display them
    Point start = new Point(0.0, 1.0);
    Point end = new Point(5.0, 6.0);
    System.out.println("Points created are " + start + " and " + end);

    // Create two lines and display them
    Line line1 = new Line(start, end);
    Line line2 = new Line(0.0, 3.0, 3.0, 0.0);
    System.out.println("Lines created are " + line1 + " and " + line2);

    // Display the intersection
    System.out.println("Intersection is " + line2.intersects(line1)); 

    // Now move the end point of line1 and show the new intersection
    end.move(1.0, -5.0);
    System.out.println("Intersection is " + line1.intersects(line2));

The program will produce the output:

Points created are 0.0, 1.0 and 5.0, 6.0
Lines created are (0.0, 1.0):(5.0, 6.0) and (0.0, 3.0):(3.0, 0.0)
Intersection is 1.0, 2.0
Intersection is 1.0, 2.0

How It Works

We first create two Point objects, which we will use later in the creation of the object line1. We then display the points using the println() method. The toString()method that we defined in the Point class is used automatically to generate the String representation for each Point object.

After creating line1 from our two points, we use the other constructor in the Line class to create line2 from two pairs of coordinates. We then display the two lines. The toString() member of the Line class is invoked here to create the String representation of each Line object, and this in turn uses the toString() method in the Point class.

The next statement calls the intersects() method from the line2 object and returns the Point object at the intersection of the two lines, line1 and line2, as part of the argument to the println() method that outputs the point. As you see, we are not obliged to save an object when we create it. Here we just use it to create the string to be displayed.

We use the move()method in the class Point to modify the coordinates of the object, end, that we used to create line1. We then get the intersection of the two lines again, this time calling the intersects() method from line1. The output result demonstrates that line1 is independent of the object end, as moving the point has made no difference to the intersection.

If you change the constructor in the Line class, to the version we saw earlier that does not create new Point objects to define the line, you can run the example again to see the effect. The output will be:

Points created are 0.0, 1.0 and 5.0, 6.0
Lines created are (0.0, 1.0):(5.0, 6.0) and (0.0, 3.0):(3.0, 0.0)
Intersection is 1.0, 2.0
Intersection is 2.0, 1.0

Changing the end object now alters the line, so we get a different intersection point for the two lines after we move the point end. This is because the Line object, line1, contains references to the Point objects defined in main(), not independent Point objects.

Previous Next
JavaScript Editor Java Tutorials Free JavaScript Editor