Reputation: 327
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?
Upvotes: 1
Views: 111
Reputation: 221
With the current definition of Function
interface, the method of
can only take in an object of type Scalar
. The Mapping
class won't compile because inheritance only work in one direction. Scalar
inherits from Space
, but the Space
doesn't inherit from Scalar
. So you can't expect the Mapping
class to be able to pass a Space
object to the method in Function
.
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 with Scalar
values. Meanwhile, the Mapping
class is expected to take in any domain of Space
type (Vector
, Scalar
, etc..). If you want your Mapping
class to accept any Space
type, then you can't limit its Function
to only accept Scalar
.
Upvotes: 0