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
Functioninterface, the methodofcan only take in an object of typeScalar. TheMappingclass won't compile because inheritance only work in one direction.Scalarinherits fromSpace, but theSpacedoesn't inherit fromScalar. So you can't expect theMappingclass to be able to pass aSpaceobject 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
Functioninterface only deals withScalarvalues. Meanwhile, theMappingclass is expected to take in any domain ofSpacetype (Vector,Scalar, etc..). If you want yourMappingclass to accept anySpacetype, then you can't limit itsFunctionto only acceptScalar.