Last active
August 29, 2015 14:13
-
-
Save dolmen/3e4ab48aa1f2baab369a to your computer and use it in GitHub Desktop.
An immutable Point class to limits bounds to [-10, 10]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// A point class must be immutable | |
class Point | |
{ | |
public final double x; | |
public final double y; | |
public Point(double x, double y) | |
{ | |
this.x = x; | |
this.y = y; | |
} | |
public Point(Point p) | |
{ | |
this.x = p.x; | |
this.y = p.y; | |
} | |
public String toString() | |
{ | |
return new StringBuilder() | |
.append('[') | |
.append(x) | |
.append(',') | |
.append(y) | |
.append(']') | |
.toString(); | |
} | |
} | |
public final class Point10 | |
extends Point | |
{ | |
public Point10(double x, double y) | |
{ | |
super(checkBounds(x), checkBounds(y)); | |
} | |
public Point10(Point p) | |
{ | |
this(p.x, p.y); | |
} | |
public Point10(Point10 p) | |
{ | |
// Bypass checks | |
super(p.x, p.y); | |
} | |
private static final double checkBounds(double coord) | |
{ | |
if (coord < -10 || coord > 10) | |
throw new IllegalArgumentException("value out of bounds"); | |
return coord; | |
} | |
// Example code | |
public static void main(String[] args) | |
{ | |
System.out.println(new Point10(4.0, 8.0)); | |
System.out.println(new Point10(4.0, 18.0)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment