user121330
user121330

Reputation: 229

Overriding methods in Java Enums with Generics

I want a typed, implementation specific method for this enumeration. The compiler doesn't like the @Override annotation, but I'm confused as to why. More importantly, how can I make a method that compares these 2 (typed) objects?

public enum BrokenToy{

    BROKEN_ARROW {
                @Override
                public <T extends Set<Object>> double compare(
                        T prop1, T prop2) {
                    return 1.0;
                }
            };

    public abstract <T> double compare(T prop1, T prop2);
}

The ideal answer would be that I've gunked up the notation, and I need to change some syntax, but alas... [sad duck-face]. This would have been another way to deal with the current challenge (Oh, it doesn't work? How perceptive). Typing within the method feels unclean, so let's look at that as a last resort.

Upvotes: 1

Views: 133

Answers (2)

yshavit
yshavit

Reputation: 43391

You can't do this with enums. In fact, you can't do it with any class.

If you could, it would break the Liskov substitution principle, which is basically that "if you can refer to an object as its super type, then you have to be able to use it as its super type."

Consider if someone did this:

BrokenToy toy = BrokenToy.BROKEN_ARROW;
double cmp = toy.compare(123, 456);

That would work according to the contract in BrokenToy, since Java would infer that T is of type Integer. But it'd fail at run time, since BROKEN_ARROW requires T to be a Set<Object>.

Instead, you should declare the generic on the class itself (which has to be an abstract, non-enum class):

public abstract class BrokenToy<T> {
    public abstract double compare(T prop1, T prop2);
    // etc
}

Upvotes: 2

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280112

The abstract compare method allows you to use any reference type as a type argument.

Your implementation in BROKEN_ARROW does not. The compiler can therefore not allow it. It would break inheritance/polymorphism.

That's why your program won't compile.

Upvotes: 4

Related Questions