Abstract Point | Point No. 1 | Point 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:
We can define a class/type called PointOnALine by adding to the JavaScript code above as follows:function Point() {}; Point.prototype = { constructor: Point, distanceFromOrigin: function() { throw new Error("Not implemented"); }, };
Then we can instantiate a new instance of a PointOnALine and invoke the concrete point's distanceFromOrigin method like this: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)); };
Try it!var p = new PointOnALine(-42); p.distanceFromOrigin();
A Java description of a point in one-dimensional space
Here is our abstract Java Point class:
We can extend this particular Point class to create a type called PointOnALine as follows:abstract class Point { Point() { } abstract double distanceFromOrigin(); }
Now we can write:class PointOnALine extends Point { double x; PointOnALine(double x) { this.x = x; } double distanceFromOrigin() { return Math.sqrt(Math.pow(this.x, 2)); } }
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. 1 | Point No. 2