扩展通用

时间:2012-11-03 22:12:05

标签: java generics inheritance polymorphism

我有一个抽象类

public abstract class Integrator {
    public abstract Point integrate();
    public abstract Point function(Double x, Point y);
}

扩展
public abstract class Euler extends Integrator {
    public Point integrate() {
        ... // this calls function(x, y)
    }
}

public abstract class Central extends Integrator {
    public Point integrate() {
        ... // this calls function(x, y)
    }
}

以不同的方式实现integrate()。现在,我实例化的具体类是这样定义的

public class EulerIVP extends Euler {
    public EulerIVP(...) { ... }

    public Point function(Double x, Point y) {
        ...
    }
}

public class CentralIVP extends Central {
    public CentralIVP(...) { ... }

    public Point function(Double x, Point y) {
        ...
    }
}

以完全相同的方式实现function(),但会使用其父级integrate()。由于EulerCentralabstract,因此扩展IVP类对他们没有意义。所以我希望我能够做这样的事情

public class IVP<T extends Integrator> extends T {
    public IVP(...) { ... }
    public Point function(Double x, Point y) { ... }
}

Integrator eulerIntegrator = new IVP<Euler>(...);
Integrator centralIntegrator = new IVP<Central>(...);

但我不能因为,我相信,T这里的类型不是一个类。有什么类似我可以做的吗?

1 个答案:

答案 0 :(得分:5)

您可以使用合成而不是继承。类似的东西:

public class IVP {
    private Integrator integrator;

    public IVP(Integrator integrator) {
        this.integrator = integrator;
    }

    public Point function(Double x, Point y) {
        // Calculate using integrator.integrate();
    }
}

然后让euler成为一个非抽象类:

IVP eulerIVP = new IVP(new Euler());