Java 中没有运算符重载。显然是出于口味的原因。真可惜。
(有些人会声称 Java 确实有重载,因为 + 和 String 可能还有自动装箱/拆箱。)
我们来谈谈值类型。
许多早期的课程(以及后来的一些课程)都把这个弄得一团糟。特别是在 AWT 中。在 AWT 中,您应该在各处显式地复制简单值。几乎可以肯定你想让值类型不可变 - 类应该是 final 并且它不应该改变状态(通常所有 final 字段都指向有效的不可变对象)。
所以:
public final class Point {
private final int x;
private final int y;
private Point(int x, int y) {
this.x = x;
this.y = y;
}
public static of(int x, int y) {
return new Point(x, y);
}
public int x() {
return x;
}
public int y() {
return y;
}
public Point add(Point other) {
return of(x+other.x, y+other.y);
}
// Standard fluffy bits:
@Override public int hashCode() {
return x + 37*y;
}
@Override public boolean equals(Object obj) {
if (!(obj instanceof Point)) {
return false;
}
Point other = (Point)obj;
return x==other.x && y==other.y;
}
@Override public String toString() {
return "("+x+", "+y+")";
}
}
原来的代码混淆了int和double,所以我选择了一个。如果你使用了double,你应该排除NaN。 “点”往往暗示一个绝对点,添加没有意义。 “矢量”或“维度”可能更合适,具体取决于您的意图。
我隐藏了构造函数,因为身份并不重要。可能值可以被缓存。例如,在零点上加一个点可能很常见,因此不需要创建点。
您可能需要一个可变版本,例如用作累加器。这应该是一个没有继承关系的单独类。可能不是在简单的情况下,但无论如何我都会展示它:
public final class PointBuilder {
private int x;
private int y;
public PointBuilder() {
}
public PointBuilder(Point point) {
this.x = point.x;
this.y = point.y;
}
public Point toPoint() {
return new Point(x, y);
}
public PointBuilder x(int x) {
this.x = x;
return this;
}
public PointBuilder y(int y) {
this.y = y;
return this;
}
public PointBuilder add(Point other) {
this.x += other.x;
this.y += other.y;
return this;
}
}