Java Classes - Point Line Polynomial
Practical exercises for week 3, building up a small set of geometry classes (Point, then Line on top of it, then an independent Polynomial) to practice java-encapsulation and java-mutability (note that movePoint/flipPoint/scale-style methods return a new object rather than mutating this).
The sheet opens with a habit it then assumes for the rest of semester:
Note on testing. From now on, whenever we ask you to write a class, you should also write a simple
mainmethod to test its functionality. This does not need to be in the same class (not every class needs amainmethod — testingclass Fooandclass Barinclass Testis fine).
On the HTML site, fill in each blank with your answer (as a quoted string, e.g. "5.0"), then click Run Code to check it. In the PDF, the Working callout is shown as a static answer key instead (interactive checking needs a browser).
Figure 1: The worked plane the first three questions build against, combining three separate plots from the week 3 practical solutions: the two points (2,3) and (4,1) of p1, the line joining them of p2, and the midpoint of p7 labelled with the formula the sheet prints. The midpoint of this particular line is (3,2).
Question 1 — Points
Write a Point class representing an x,y-coordinate on a Cartesian plane. A Point stores two floats, one for each coordinate, with:
Point(float x, float y)and a defaultPoint()(both 0).float getX()/float getY().Point movePoint(float deltaX, float deltaY)— returns a newPointat(getX() + deltaX, getY() + deltaY). The sheet emphasises: this method should not modify thePointit is called on.static double distance(Point p, Point q)— Euclidean distance between \(p = (x_1, y_1)\) and \(q = (x_2, y_2)\):
\[d\big((x_1,y_1),(x_2,y_2)\big) = \sqrt{(x_1-x_2)^2 + (y_1-y_2)^2}\]
If p1 = new Point() and p2 = p1.movePoint(4, 5), what does p2 print (assuming a toString of "(" + x + ", " + y + ")")?
public class Point {
private float x;
private float y;
public Point() {
this(0, 0);
}
public Point(float x, float y) {
this.x = x;
this.y = y;
}
public float getX() { return this.x; }
public float getY() { return this.y; }
public Point movePoint(float deltaX, float deltaY) {
return new Point(this.x + deltaX, this.y + deltaY);
}
public static double distance(Point p, Point q) {
double x = p.x - q.x;
double y = p.y - q.y;
return Math.sqrt(x * x + y * y);
}
@Override
public String toString() {
return "(" + x + ", " + y + ")";
}
}Three details in the model answer worth copying:
- The default constructor is written
this(0, 0)— constructor chaining — rather than repeating the two assignments. One place initialises the fields. movePointdeliberately returns a newPointrather than mutatingthis, sop1is left at(0.0, 0.0)andp2is(4.0, 5.0).distanceisstaticand readsp.xandq.xdirectly, not throughgetX(). That compiles becauseprivatein Java is per-class, not per-object: anyPointmethod can reach any otherPoint’s private fields.
Question 2 — Lines
Write a Line class storing a start Point, an end Point, and the (precomputed) double length between them, with:
Line(Point start, Point end)— also stores the distance between the two points — and a defaultLine()(both ends at the origin, length 0).getStart()/getEnd()/getLength().void moveStart(float deltaX, float deltaY)/void moveEnd(float deltaX, float deltaY)— mutator methods that move the line’s start/end by the given values.
For a Line from (0, 0) to (3, 4), what is getLength()?
public class Line {
private Point start;
private Point end;
private double length;
public Line() {
this.start = new Point();
this.end = new Point();
this.length = 0;
}
public Line(Point start, Point end) {
this.start = start;
this.end = end;
this.length = Point.distance(start, end);
}
public Point getStart() { return start; }
public Point getEnd() { return end; }
public double getLength() { return length; }
public void moveStart(float deltaX, float deltaY) {
start = start.movePoint(deltaX, deltaY);
length = Point.distance(start, end);
}
public void moveEnd(float deltaX, float deltaY) {
end = end.movePoint(deltaX, deltaY);
length = Point.distance(start, end);
}
@Override
public String toString() {
return start.toString() + " " + end.toString() + " " + this.getLength();
}
}(0,0) to (3,4) is a 3-4-5 right triangle, so the length is exactly 5.0.
Note the two designs sitting side by side, deliberately: Point.movePoint is immutable (returns a new object, void nowhere in sight) while Line.moveStart/moveEnd are mutators (void, changing this). moveStart is written on top of the immutable one — start = start.movePoint(...) builds a fresh Point and rebinds the field to it, rather than reaching into the old Point and editing it.
length is a derived field: it is not independent state, it is a cached function of start and end. That is why every method that touches an endpoint has to recompute it on the next line. Storing it at all is a choice the sheet makes for you (the question says a Line stores “a double representing the length”), and the recomputation is the price — see java-encapsulation on keeping an object’s fields consistent with each other.
Question 3 — Testing and toString
Unless overridden, printing an object prints its class name and memory location, e.g. Point@30f39991 — the class name Point plus the location in memory 30f39991. Writing a toString() that returns a String overrides that default when a class instance is converted to a string, and makes testing by eye possible at all.
The sheet’s own reason for doing this now rather than later: “Now is a good opportunity to test your program, if you haven’t already. It is a bad idea to write too much code before checking that it works.”
Point p1 = new Point();
Point p2 = p1.movePoint(4, 5);
System.out.println(p1); // (0.0, 0.0)
System.out.println(p2); // (4.0, 5.0)Line’s version delegates to Point’s rather than reaching for start.getX() and friends:
@Override
public String toString() {
return start.toString() + " " + end.toString() + " " + this.getLength();
}Question 4 — Additional methods
Add to Point:
Line createLine(Point end)— aLinewiththisas the start andendas the end.Point flipPoint()— returns a new object with the sign of both coordinates changed, e.g. \((-1, 2)\) becomes \((1, -2)\).
Add to Line:
Point middle()— the midpoint of the start and end, at \(\left(\frac{x_1+x_2}{2}, \frac{y_1+y_2}{2}\right)\).Line flipLine()— a newLinewith both endpoints flipped as above.
What does new Point(-1, 2).flipPoint() print?
Figure 2: What flipping means geometrically, redrawing the two plots the week 3 practical solutions use to define it (p6 for the point, p7 for the line) side by side in one frame. Left: flipPoint negates both coordinates, so (-1,2) lands at (1,-2) - a 180-degree rotation about the origin, not a reflection in either axis. Right: flipLine is just that applied to both endpoints, sending the blue line (2,3)-(4,1) to the red line (-2,-3)-(-4,-1). The colours are the sheet’s.
On Point:
public Line createLine(Point end) {
return new Line(this, end);
}
public Point flipPoint() {
return new Point(x * -1, y * -1);
}On Line:
public Point middle() {
return new Point((start.getX() + end.getX()) / 2,
(start.getY() + end.getY()) / 2);
}
public Line flipLine() {
return new Line(start.flipPoint(), end.flipPoint());
}Each of the four is a one-liner because the layer beneath it already exists: createLine hands this to a constructor, flipLine is flipPoint applied twice, middle is arithmetic on accessors. This is the payoff for having written Point properly first.
Note flipLine does not mutate — consistent with flipPoint and movePoint, and inconsistent with moveStart/moveEnd, which do. The class ends up with both conventions in it; the sheet does not reconcile them.
Question 5 — Polynomials (bonus)
A polynomial function specifies lines and curves on a Cartesian plane in terms of its coefficients:
Figure 3: The four example polynomials plotted in the week 3 practical solutions p8, redrawn with the sheet’s own colour coding and its full a + bx + cx^2 spellings alongside the collapsed forms. The point of the figure is that a straight line, a horizontal line and a parabola are all the same object here - only the three coefficients differ. The colour-keyed equation list is placed inside the figure rather than beside it as the sheet does.
In general a polynomial function has the form
\[f(x) = a_0 + a_1x + a_2x^2 + \dots + a_{n-1}x^{n-1} + a_nx^n\]
where \(a_0 \dots a_n\) are its coefficients. For this exercise it is restricted to \(f(x) = a + bx + cx^2\).
Write a Polynomial class represented by its coefficients, with constructors Polynomial() (giving \(f(x) = 0\)), Polynomial(float a), Polynomial(float a, float b), Polynomial(float a, float b, float c), plus:
float valueAt(float x)— the value of the polynomial at \(x\).Polynomial add(Polynomial other)— a newPolynomialfor \(f_1(x) + f_2(x) = (a_1 + a_2) + (b_1 + b_2)x + (c_1 + c_2)x^2\).
For \(f(x) = 1 + 2x\), what is \(f(3)\)?
\(f(3) = 1 + 2 \times 3 = 7\).
The model answer stores a float[] from the start, so it already solves the challenge below; the four “restricted” constructors are just convenience wrappers over one array:
import java.util.StringJoiner;
public class Polynomial {
private final float[] coefficients;
public Polynomial() { coefficients = new float[]{0}; }
public Polynomial(float a) { coefficients = new float[]{a}; }
public Polynomial(float a, float b) { coefficients = new float[]{a, b}; }
public Polynomial(float a, float b, float c) { coefficients = new float[]{a, b, c}; }
public Polynomial(float[] coefficients) { this.coefficients = coefficients; }
private static float index(float[] coefficients, int index) {
/* The value of coefficients with index greater than
* the maximum index of the polynomial is 0. */
if (index >= coefficients.length) {
return 0;
}
return coefficients[index];
}
public Polynomial add(Polynomial other) {
int max = Math.max(coefficients.length, other.coefficients.length);
float[] newCoefficients = new float[max];
for (int i = 0; i < max; i++) {
newCoefficients[i] = index(coefficients, i)
+ index(other.coefficients, i);
}
return new Polynomial(newCoefficients);
}
public float valueAt(float x) {
float v = 0;
float xpower = 1;
for (int i = 0; i < coefficients.length; i++) {
/* xpower = x^i */
v += coefficients[i] * xpower;
xpower *= x;
}
return v;
}
@Override
public String toString() {
StringJoiner builder = new StringJoiner(" + ");
for (int i = 0; i < coefficients.length; i++) {
builder.add(coefficients[i] + "x^" + i);
}
return builder.toString();
}
}Three things the model answer is doing on purpose:
private static float index(...)exists soaddcan read past the end of the shorter array without anifin the loop body — a coefficient that isn’t stored is \(0\). Without it,addwould need a length check per term.valueAtcarriesxpoweralong instead of callingMath.pow(x, i)each iteration: one multiply per term rather than a power computation per term. (Recognisably Horner-adjacent, though the sheet does not name it.)coefficientsisfinal, so aPolynomialcannot be re-pointed at a different coefficient array after construction — which is what letsaddsafely return a new instance rather than worrying about shared state. Note thePolynomial(float[])constructor still stores the caller’s array by reference, so the contents are not protected; see java-mutability.
toString uses StringJoiner(" + "), which inserts the separator only between items — so a one-term polynomial prints without a trailing +.
Challenge — representing the unrestricted \(f(x) = a_0 + a_1x + \dots + a_nx^n\) for any \(n \geq 0\) needs no new code: valueAt, add and toString are all written against coefficients.length, and the Polynomial(float[]) constructor already accepts an array of any length.
Testing it end to end
The sheet’s own Main sweeps each polynomial across \(x \in [-10, 10)\) and prints the line, which is how you check Figure 3 by eye rather than by trust:
public class Main {
private static void testPoints(Polynomial p) {
for (int x = -10; x < 10; x++) {
System.out.print(p.valueAt(x) + " ");
}
System.out.println();
}
public static void main(String[] args) {
Point p1 = new Point();
Point p2 = p1.movePoint(4, 5);
System.out.println(p1);
System.out.println(p2);
Line line = new Line(p1, p2);
System.out.println(line);
Polynomial acrossZero = new Polynomial();
testPoints(acrossZero);
Polynomial acrossTwo = new Polynomial(2);
testPoints(acrossTwo);
Polynomial diag = new Polynomial(1, 2);
testPoints(diag);
Polynomial slope = new Polynomial(2, -2);
testPoints(slope);
Polynomial parab = new Polynomial(1, 0, 0);
testPoints(parab);
System.out.println(parab);
System.out.println(slope);
}
}Note new Polynomial(1, 0, 0) is named parab but is \(f(x) = 1\), a flat line — the coefficients are in ascending order (\(a\), then \(b\), then \(c\)), so the parabola would be new Polynomial(0, 0, 1). (That reading is mine, not the sheet’s; the sheet prints the listing without comment. It is a good illustration of why toString is worth writing: running this prints 1.0x^0 + 0.0x^1 + 0.0x^2 and the mistake is visible immediately.)