How to implement an interface with an enum, where

2020-02-28 04:14发布

Consider this code:

public interface Foo extends Comparable<Foo> {}

public enum FooImpl implements Foo {}

Due to the restrictions of type erasure, I receive the following error:

java.lang.Comparable cannot be inherited with different arguments: <Foo> and <FooImpl>

I have the following requirements:

  • FooImpl needs to be an enum, because I need to use it as a default value in annotations.
  • The contract of my interface is that it needs to be comparable.

I already tried using generic bounds in the interface, but this is not supported in Java.

3条回答
男人必须洒脱
2楼-- · 2020-02-28 04:17

Actually the error you will get is :

The interface Comparable cannot be implemented more than once with different arguments : Comparable<FooImpl> and Comparable<Foo>

As enum FooImpl already implementing Comparable<FooImpl> implicitly, you can not override it again as Comparable<Foo>.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2020-02-28 04:19

Enum already implements comparable so you can't override it.

A general answer regarding why-would-an-enum-implement-an-interface.

查看更多
Melony?
4楼-- · 2020-02-28 04:37

Enums implement Comparable, so FooImpl ends up extending Comparable twice with incompatible arguments.

The following will work:

public interface Foo<SelfType extends Foo<SelfType>> extends Comparable<SelfType> { ... }

public enum FooImpl implements Foo<FooImpl> { ... }
查看更多
登录 后发表回答