Reputation: 1795
I defined a simple base interface, holding one method with a abstract class as parameter.
public interface IVisitor {
void visit(BaseVehicle vehicle);
}
This base interface can be extended by another interface, which should be able to overload this method from the base interface several times with more specific classes.
public interface ISpecificVisitor extends IVisitor {
void visit(TruckCar car);
void visit(Lory car);
}
Can one write the base interface with generics so that the sub interface can/must overload with a more specific class? If yes, how would that look like?
Upvotes: 0
Views: 127
Reputation: 10322
You can do it, but because of type erasure, you cannot do it in an elegant way:
public interface Vehicle {}
public class Car implements Vehicle {}
public class Boat implements Vehicle {}
public interface IVisitor<C extends Vehicle, B extends Vehicle> {
// These methods have the same erasure, compile time error.
// void visit(C vehicle);
// void visit(B vehicle);
// ugly workaround.
void visitC(C vehicle);
void visitB(B vehicle);
}
public class SpecificVisitor implements IVisitor<Car, Boat> {
@Override
public void visitC(Car vehicle) {}
@Override
public void visitB(Boat vehicle) {}
}
Upvotes: 0
Reputation: 2644
This should work for you:
public interface IVisitor<T extends BaseVehicle> {
void visit(T vehicle);
}
Upvotes: 7