Is there a way to make sure classes implementing an Interface implement static methods?
Posted
by Tobias Kienzler
on Stack Overflow
See other posts from Stack Overflow
or by Tobias Kienzler
Published on 2010-04-22T08:40:06Z
Indexed on
2010/04/22
8:43 UTC
Read the original article
Hit count: 168
Frist of all, I read erickson's usefull reply to "Why can’t I define a static method in a Java interface?". This question is not about the "why" but about the "how then?".
So basically I want one Interface to provide both usual methods and e.g. a getSimilarObject
method. For (a made up) example
public interface ParametricFunction {
/** @return f(x) using the parameters */
static abstract public double getValue(double x, double[] parameters);
/** @return The function's name */
static abstract public String getName();
}
and then
public class Parabola implements ParametricFunction {
/** @return f(x) = parameters[0] * x² + parameters[1] * x + parameters[2] */
static public double getValue(double x, double[] parameters) {
return ( parameters[2] + x*(parameters[1] + x*parameters[0]));
}
static public String getName() { return "Parabola"; }
}
Since this is not allowed in the current Java standard, what is the closest thing to this?
The idea behind this is putting several ParametricFunction
's in a package and use Reflection to list them all, allowing the user to pick e.g. which one to plot. Obviously one could provide a loader class containing an array of the available ParametricFunction
's, but every time a new one is implemented one has to remember adding it there, too.
© Stack Overflow or respective owner