Home > OS >  Java - How to create generic abstract method that accepts different enums?
Java - How to create generic abstract method that accepts different enums?

Time:08-09

How can I create abstract generic method doSomething() that accepts different enums? Enum1 and Enum2, Enum3 and so on?

public abstract class NumerOne {

public abstract void doSomething();

}

public class NumberTwo extends NumberOne {

@Override
public void doSomething (Enum1 enum1) {
 enum1.createSomething();
}

CodePudding user response:

The most appropriate way to accept a handful of Enum types, but not accept any enum (<T extends Enum<T>) or (even worse) Object would be to create an interface and have all the enums that you want to accept implement that interface:

interface CreatorOfSomething {
    // I have no idea what type should be returned here,
    // as you don't use this value in your example.
    // But I'm pretty sure it can't be void, so I'll go with Integer.
    // You can have this parameterised as <T> at the interface level.
    Integer createSomething();
}

enum Enum1 implements CreatorOfSomething {
    A, B, C;
    @Override
    public Integer createSomething() {
        return ordinal();
    }
}

enum Enum2 implements CreatorOfSomething {
    X { // you can override the method for individual constants
        @Override
        public Integer createSomething() {
            // .....
        }
    },
    Y { ....
}

Then your method would look like:

public void doSomething(CreatorOfSomething creator) {
    creator.createSomething();
}

CodePudding user response:

The code you posted does not even compile. Nor could we run it. Next time please provide an SSCCE in which you address your question.

Here's the solution for the problem you have:

abstract class NumberOne {
    public abstract <T extends Enum<T>> void doSomething(T pEnum);
}

enum Enum1 {
    A, B
}
enum Enum2 {
    C, D
}

public class NumberTwo extends NumberOne {

    @Override public <T extends Enum<T>> void doSomething(final T pEnum) {
        System.out.println("Value: "   pEnum);
    }

    public static void main(final String[] args) {
        final NumberTwo n2 = new NumberTwo();
        n2.doSomething(Enum1.A);
        n2.doSomething(Enum2.D);
    }

}
  • Related