Abstract Point | Point No. 1 | Point No. 2
In “Concrete Point No. 1” we extended abstract notions of a point that were presented in “An Abstract Point” into concrete JavaScript and Java classes that model a point in one-dimensional space. In this post we continue the pattern by extending those classes with corresponding models of a point in two-dimensional space!
A JavaScript description of a point in two-dimensional space
Given:
We can compose:// A class that models an abstract point function Point() {}; Point.prototype = { constructor: Point, distanceFromOrigin: function() { throw new Error("Not implemented"); }, }; // A class that models a point in one dimension 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)); };
And then we can do things like:// A class that models a point in two dimensions function PointInAPlane(x, y) { PointOnALine.call(this, x); this.y = y; }; PointInAPlane.prototype = Object.create(PointOnALine.prototype); PointInAPlane.prototype.constructor = PointInAPlane; PointInAPlane.prototype.distanceFromOrigin = function() { return Math.sqrt(Math.pow(this.x, 2) + Math.pow(this.y, 2)); };
A Java description of a point in two-dimensional space
Given:
We can compose:// A class that models an abstract point abstract class Point { Point() { } abstract double distanceFromOrigin(); } // A class that models a point in one-dimensional space class PointOnALine extends Point { double x; PointOnALine(double x) { super(); this.x = x; } double distanceFromOrigin() { return Math.sqrt(Math.pow(this.x, 2)); } }
And then we can compose code that uses our classes. For example:// A class that models a point in two-dimensional space class PointInAPlane extends PointOnALine { double y; PointInAPlane(double x, double y) { super(x); this.y = y; } double distanceFromOrigin() { return Math.sqrt(Math.pow(this.x, 2) + Math.pow(this.y, 2)); } }
Finally, we can compile and interpret our code!class TestPoint { public static void main(String[] args) { Point p1 = new PointInAPlane(3, 4); Point p2 = new PointInAPlane(4, 5); System.out.println(p1.distanceFromOrigin()); System.out.println(p2.distanceFromOrigin()); } }
Abstract Point | Point No. 1 | Point No. 2