I have:
abstract class Vehicleabstract class Car extends Vehicle and abstract class Truck extends VehicleDodgeRam extends Truckinterface DumpNow 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 Vehicles:
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();
}
}
This is possible now in java 17.
public sealed interface TestInterface permits TestClass1, Testclass2 {
}
No, interfaces are always intended to provide public prototype we can not restrict the classes to implement the interfaces.
One thing you can try is.. you can define the Dump interface in class Truck and make the Truck class package scope instead of public and keep all the sub classes of Truck in the same package. so that no other class can access Truck class so that no other class can implement Dump interface. - This is not tried but guess it works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With