我是否可以要求实现接口的类具有某个静态字段或方法,并通过泛型类型参数访问/调用该字段或方法?
我有一个接口Arithmetical< T>,它指定了几个函数,如T plus(T o)和T times(T o).我也有一个Vector< N extends Arithmetical< N>> class,用于具有类型N的组件的向量(具有可变维度).但是,当尝试实现dot product时,我遇到了一个问题.
我想实现方法N dot(Vector< N> o).为此,我计划从任何N的零开始并迭代两个Vector< N> s’List< N> s,将每对元素的乘积添加到我的总数中.有没有办法在Arithmetical中指定< T>所有实现类必须具有静态(并且最好是最终的)字段ZERO并且开始点(向量< N> o)的主体具有沿着N sum = N.ZERO的行;
如果没有,那么这个问题还有什么其他方法呢?我想允许0维向量,所以我不能仅仅通过将向量的第一个组件相乘来开始.有没有办法实例化泛型类型的对象,所以我只能在Arithmetical< T>中指定一个T zero()方法?
我有理由不使用Java的数字类型 – 我希望有复杂组件的向量.
这是算术:
public interface Arithmetical {
public T plus(T o);
public T minus(T o);
public T negate();
public T times(T o);
public T over(T o);
public T inverse();
// Can I put a line here that requires class Complex (below) to define ZERO?
}
向量:
public class Vector> {
private List components;
public Vector(List cs) {
this.components = new ArrayList(cs);
}
public N dot(Vector o) {
// Here's where I need help.
}
}
复杂:
public class Complex implements Arithmetical {
public static final Complex ZERO = new Complex(0, 0); // Can I access this value through N if >?
private double real;
private double imag;
public Complex(double r, double i) {
this.real = r;
this.imag = i;
}
/* Implementation of Arithmetical (and some more stuff) not shown... */
}
我对Java(以及一般的编程)很陌生;我可能不会理解复杂的(ha)解释和解决方法.
谢谢!
(Python是建议的标签… Huh.)