0

Let's assume I have some enum:

enum Resource { FILE, URL, STREAM }

Let's assume I have some Reader interface:

interface Reader<R extends Resource>

Is it possible to create different implementations of it using Enum Members? Like that:

class FileReader implements Reader<Resource.FILE>

My ide highlights this text with red (which is not a big surprise).

1
  • 2
    Short answer, no, long answer, making a method in your enumerated and override in each enumerated value might be a solution Commented Jan 20, 2014 at 7:47

2 Answers 2

2

Enum members are instances of enum type, not subclasses. Moreover, enums can't be subclassed. Thus, you can't compile your code.

I suggest you to write this way:

interface Reader {
    Resource getResource()
    ....
}

class FileReader implements Reader {
    @Override
    public Resource getResource() {return Resource.FILE;}
    ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

Enum members can actually be subclasses of the enum type, if they declare a class body (ie, if the enum name is followed by curly braces). But this extended class is an anonymous class, and as such has no name and can't be referenced in a generic declaration. See JLS 8.9.1.
1

As Alexander Tokarev mentioned, you can't do this. An alternative to his approach is to roll your own enum-like classes by extending nested classes from a base class that has a private constructor:

public class Resource {
    private Resource() {}

    // some methods, abstract methods, etc...

    public static class File extends Resource {
      private File() {}

      // etc...
    }

    private static final File FILE = new File();

    // other subclasses of Resource
}

Now you can use generics as usual:

interface Reader<R extends Resource> {...}
class FileReader implements Reader<Resource.File> {...}

This gives you many of the advantages that enums have -- type safety, a closed set of values, etc -- while explicitly setting up a class hierarchy that you can use with generics. The major cost is in brevity of code, though you also lose the ability to use the values in switch statements, as well as some other, more esoteric benefits of enums.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.