Matthew S.
Matthew S.

Reputation: 721

Casting enums in a class

I have five cases of enums that look like this one below:

public enum Answers{
    A(0), B(1), C(2), D(3), E(4);

    Answers(int code){
        this.code = code;
    }

    protected int code;

    public int getCode(){
        return this.code;
    }
}

They all are all virtually the same except consisting of different "codes" and enumerators. I now have this following class where the generic is an extension of an Enum, however, I need to be able to use the getCode(), which is only in my enums, not a basic enum.

public class test<T extends Enum>{
    public void tester(T e){
        System.out.println(e.getCode()); //I want to be able to do this, 
                                         //however, the basic enum does don't
                                         //have this method, and enums can't extend
                                         //anything.
    }
}

Thank you

Upvotes: 0

Views: 117

Answers (4)

Pshemo
Pshemo

Reputation: 124215

If that is the only method you want to add to your Enum then you don't have to do it. Every Enum already has ordinal method which returns value that represents it position in Enum. Take a look at this example

enum Answers{
    A,B,C,D,E;
}

class EnumTest<T extends Enum<T>>{
    public void tester(T e){
        System.out.println(e.ordinal()); 
    }

    public static void main(String[] args) throws Exception {
        EnumTest<Answers> t = new EnumTest<>();
        t.tester(Answers.A);
        t.tester(Answers.B);
        t.tester(Answers.E);
    }
}

Output:

0
1
4

Upvotes: 1

rgettman
rgettman

Reputation: 178253

Have your enum classes implement your own HasCode interface:

public interface HasCode {
    public int getCode();
}

public enum Answers implements HasCode {
//...

Then you can restrict T to be a HasCode:

public class test<T extends HasCode>{

and then Java will recognize that anything, even an enum, as long it implements HasCode, will have a getCode() method and it can be called in tester.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500055

You can make your enums implement an interface:

public interface Coded {
    int getCode();
}

Then:

public enum Answers implements Coded {
    ...
}

And:

public class Test<T extends Enum & Coded> {
    public void tester(T e) {
        System.out.println(e.getCode());
    }
}

Upvotes: 3

JB Nizet
JB Nizet

Reputation: 691655

Make all your enums implement a common interface:

public interface HasCode {
    int getCode();
}

public enum Answers implements HasCode {
    ...
}

And then

public class Test<T extends HasCode> {

Upvotes: 2

Related Questions