Pages

Tuesday, September 27, 2016

Concrete Point No. 1

Abstract Point | Point No. 1Point No. 2

In “An Abstract Point” we explored ways to represent the abstract notion of a point using JavaScript and Java. Now we'll look at JavaScript and Java classes that model a concrete point in one-dimensional space.

A JavaScript description of a point in one-dimensional space


Previously we defined a JavaScript class/type called Point like this:
function Point() {};
Point.prototype = {
  constructor: Point,
  distanceFromOrigin: function() {
    throw new Error("Not implemented");
  },
};
We can define a class/type called PointOnALine by adding to the JavaScript code above as follows:
function PointOnALine(x) {
  Point.call(this);
  this.x = x;
};
PointOnALine.prototype = Object.create(Point.prototype);
PointOnALine.prototype.constructor = PointOnALine;
PointOnALine.prototype.distanceFromOrigin = function() {
  return Math.sqrt(Math.pow(this.x, 2));
};
Then we can instantiate a new instance of a PointOnALine and invoke the concrete point's distanceFromOrigin method like this:
var p = new PointOnALine(-42);
p.distanceFromOrigin();
Try it!

A Java description of a point in one-dimensional space


Here is our abstract Java Point class:
abstract class Point {
  Point() {
  }
  abstract double distanceFromOrigin();
}
We can extend this particular Point class to create a type called PointOnALine as follows:
class PointOnALine extends Point {
  double x;
  PointOnALine(double x) {
    this.x = x;
  }
  double distanceFromOrigin() {
    return Math.sqrt(Math.pow(this.x, 2));
  }
}
Now we can write:
abstract class Point {
  Point() {
  }
  abstract double distanceFromOrigin();
}
class PointOnALine extends Point {
  double x;
  PointOnALine(double x) {
    super();
    this.x = x;
  }
  double distanceFromOrigin() {
    return Math.sqrt(Math.pow(this.x, 2));
  }
}
class TestPoint {
  public static void main(String[] args) {
    Point p = new PointOnALine(-42);
    double d = p.distanceFromOrigin();
    System.out.println(d);
  }
}

Abstract Point | Point No. 1Point No. 2