I'm trying to use type erasure in order to access the inherited methods of the general type.
I have a parent class, Space, and child classes, Scalar, Vector, Mapping, etc. I want an interface, Function, for which I can specify the domain and range among the various child classes of Space.
The class, Mapping, contains the interface, Function, and should be able to access it through the method, Of.
If the programmer wants to take the mapping of a double, i.e.,
Mapping map = new Mapping(...);
Scalar answer = map(0.0);
then I want the function, Of, to convert the double to a Scalar and then pass it on to the interface, Function.
public class Mapping<Domain extends Space, Range extends Space> extends Space{
protected Function<Domain,Range> function;
public Range of(Double point){
return function.of(new Scalar(point)); //Error, the type <Domain,Range> is not applicable to type Scalar.
}
}
public interface Function<Domain extends Space,Range extends Space>{
public Range of(Domain point);
}
public class Scalar extends Space {
protected double value=0.0;
public Scalar(double in){
value = in;
}
Eclipse recommends casting Scalar to Domain, but since Domain extends Space, as does Scalar, shouldn't a Scalar be acceptable to pass to Function?
Edit:
I have constructors for each child class that take in Scalar as an argument, e.g., Public Vector(Scalar x){...}
. I want Mapping
to take in a double, convert it to a Scalar
, and then if the Domain
of the function is, for example, a Vector, then I would like the Vector(Scalar x)
constructor called.
Ideally, I would just have a parent constructor of a double:
public Range of(Double point){
return function.of(new Domain(point));
}
But I can't implement a generic type. This is the problem I'm trying to work around. Is there a better way of doing this?
With the current definition of
Function
interface, the methodof
can only take in an object of typeScalar
. TheMapping
class won't compile because inheritance only work in one direction.Scalar
inherits fromSpace
, but theSpace
doesn't inherit fromScalar
. So you can't expect theMapping
class to be able to pass aSpace
object to the method inFunction
.The design of your classes need some refactoring, but it's not clear what you want to achieve, because the design is conflicting with itself.
For example, the
Function
interface only deals withScalar
values. Meanwhile, theMapping
class is expected to take in any domain ofSpace
type (Vector
,Scalar
, etc..). If you want yourMapping
class to accept anySpace
type, then you can't limit itsFunction
to only acceptScalar
.