Skip to content

Instantly share code, notes, and snippets.

@dolmen
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dolmen/3e4ab48aa1f2baab369a to your computer and use it in GitHub Desktop.
Save dolmen/3e4ab48aa1f2baab369a to your computer and use it in GitHub Desktop.
An immutable Point class to limits bounds to [-10, 10]
// 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