I have:
abstract class Vehicle
abstract class Car extends Vehicle
andabstract class Truck extends Vehicle
DodgeRam extends Truck
interface Dump
Now I want to limit Dump
interface so that it can only be implemented by subclasses of Truck
, without explicitly saying that Truck implement Dump
. How can I do this?
I thought I could just change Dump
to interface Dump<T extends Truck>
and then say DodgeRam implements Dump<DodgeRam>
. The problem is that nothing stops me from saying ToyotaCamary implements Dump
and just leaving off the type.
UPDATE:
The reason I'm doing this is because I want to avoid a lot of type checking/casting. Let's say my Truck
has an isOffRoad
property:
public class Truck {
private boolean isOffRoad;
public Truck(boolean isOffRoad) {
this.isOffRoad = isOffRoad;
}
public boolean isOffRoad() {
return isOffRoad;
}
}
Let's say I also have a Dealership
which manages my list of Vehicle
s:
public class Dealership {
List<Truck> getTrucks() {...}
List<Dump>getDumpers() {...}
}
Now I want to check the Offroad capabilities of all of my "dump trucks":
for (Dump dump: dealership.getDumpers() ) {
print dump.isOffRoad();
}
I don't want to have to typecheck / cast every time:
for (Dump dump: dealership.getDumpers() ) {
if (dump instanceOf Truck) {
print ((Truck)dump).isOffRoad();
}
}