Reputation: 814
I have an abstract class
public abstract class Integrator {
public abstract Point integrate();
public abstract Point function(Double x, Point y);
}
which is extended by
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)
}
}
which both implement integrate()
differently. Now, the concrete classes which I instantiate are defined like so
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) {
...
}
}
which both implement function()
exactly the same way, but will use their parent's integrate()
. Because Euler
and Central
are abstract
it doesn't make sense for them to both extend an IVP
class. So I was hoping I'd be able to do something like this
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>(...);
But I can't because, I believe, T
here would be a type not a class. Is there something similar I can do?
Upvotes: 1
Views: 129
Reputation: 18569
You can use composition instead of inheritance. Something like:
public class IVP {
private Integrator integrator;
public IVP(Integrator integrator) {
this.integrator = integrator;
}
public Point function(Double x, Point y) {
// Calculate using integrator.integrate();
}
}
and then make euler a non-abstract class:
IVP eulerIVP = new IVP(new Euler());
Upvotes: 5