Martijn Burger
Martijn Burger

Reputation: 7543

How to lock down a generic type which is an enum

I have a problem locking down a generic type. Below is an interface that is implemented by two enum classes. The Cover class is using a generic type, which is specified in a CarRequest class. I want to be able to use only the enums that implement the CoverType interface.

At first I thought of using an abstract class that is extended by the enums and use:

public class Cover<T extends AbstractCoverType>

But that does not work, because I cannot extend an enum class. Than I thought of the interface solution that is presented below, however in that case I cannot do:

public class Cover<T implements CoverType>

How can I lock down the Cover class to only accept as a generic type the first two enums and not the third?

Interface:

public interface CoverType {}

First enum:

public enum FireCoverType implements CoverType {
    SANITATION, RENTAL, GLASS
}

Second enum:

public enum CarCoverType implements CoverType {
    ACCESSORIES, LEGAL_ASSISTANCE
}

Third enum:

public enum PaymentTerm {
    MONTH, QUARTER, YEAR
}

Cover class:

public class Cover<T> {
    private T coverType;
    // getter and setter
}

CarRequest:

public class CarRequest {
    private Cover<CarCoverType> cover;
    // getter and setter
}

Upvotes: 1

Views: 324

Answers (1)

Mena
Mena

Reputation: 48434

Use extends when binding your generic type definition, regardless of whether it's an class or an interface.

In other words, there's no implements in generic type upper-binding - extends works for both classes and interfaces.

So:

public class Cover<T extends CoverType>

... is the solution you're looking for, where CoverType is the interface your enums implement.

From the documentation:

Note that [...] extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces).

Also worth noting, enums can't extend classes, as they implicitly extend java.lang.Enum already.

Upvotes: 6

Related Questions