【发布时间】:2015-06-10 17:58:33
【问题描述】:
我无法将构建在彼此之上的多个向量类链接起来。我希望能够扩展该类。
这是二维的:
public class Vec2 < C extends Vec2 > {
public double x, y;
public Vec2() {
}
public Vec2(double x, double y) {
this.x = x;
this.y = y;
}
public C add(double x, double y) {
this.x += x;
this.y += y;
return (C) this;
}
}
这是一个带有 z 元素的向量。
class Vec3 < C extends Vec3 > extends Vec2<Vec3> {
double z;
public Vec3(){}
public Vec3(double x, double y, double z) {
super(x, y);
this.z = z;
}
public C add(double x, double y, double z) {
super.add(x, y);
this.z += z;
return (C) this;
}
}
但是什么时候使用 Vec3,那么只要我连续两次使用 Vec2 中的方法,它就会返回 Vec2。
Vec3<Vec3> a = new Vec3<>();
// ------------------------------------------------->.add() in Vec2 cannot be aplied
a.add(10, 20).add(10, 20, 10).add(10, 20).add(10, 20).add(10, 10, 20);
我不想这样写课程:
class Vec3 extends Vec2<Vec3> {
// constructor etc. like before...
public Vec3 add(double x, double y, double z) {
super.add(x, y);
this.z += z;
return this;
}
}
因为当我制作 Vec4 时,我必须覆盖 Vec3 中的每个方法。
有没有办法(语法)解决这个问题?无论如何它都会返回正确的类。
【问题讨论】:
-
This,不过不知道能降多少级。
-
我认为你不能走得太远,而这个 无论在哪里它总是返回正确的类,如果没有开发人员的参与几乎是不可能的。
标签: java inheritance chaining