tir38
tir38

Reputation: 10421

Can I limit which classes can implement an interface?

I have:

  1. abstract class Vehicle
  2. abstract class Car extends Vehicle and abstract class Truck extends Vehicle
  3. DodgeRam extends Truck
  4. 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 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();
    }
}

Upvotes: 2

Views: 1819

Answers (4)

Krushna
Krushna

Reputation: 6060

This is possible now in java 17.

public sealed interface TestInterface permits TestClass1, Testclass2 {

}

Upvotes: 2

Spotted
Spotted

Reputation: 4091

If you want only Truck to implement Dump then an interface is not the right tool to do that job.

Instead, you have to declare the methods that are present in Dump into Truck (either abstract or not depending if the implementation makes sense at this level).

Example:

If Dump is public interface Dump { void foo(); }

Then Truck should be public abstract class Truck { public abstract void foo(); }

That way you don't implement Dump and only subclasses of Truck can implement foo().

Upvotes: 1

Pavan
Pavan

Reputation: 858

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.

Upvotes: 2

ryonts
ryonts

Reputation: 126

interfaces are public by definition, therefore anything can implement them. perhaps if you explained what your real goal is, there may be some other way to achieve it

Upvotes: 1

Related Questions