I have 2 or more enums with the same methods in each. I need to use all these enums to validate a message in another class. Each enum have the same methods. I understand how to pass an enum as a generic parameter but I don't believe it is then possible to call that enum's method in the method that receives the enum as a generic enum.
            Asked
            
        
        
            Active
            
        
            Viewed 43 times
        
    1
            
            
        - 
                    1Share some code – azro Feb 21 '18 at 08:26
- 
                    7Use interfaces. Enums can implement interfaces. – Erwin Bolwidt Feb 21 '18 at 08:26
- 
                    2[Why would an Enum implement an Interface?](https://stackoverflow.com/questions/2709593/why-would-an-enum-implement-an-interface) – Erwin Bolwidt Feb 21 '18 at 08:28
1 Answers
1
            
            
        Just like other classes, enums can implement interfaces.
interface CanThing {
    void doThing(); 
}
enum Validate implements CanThing {
    ONE_THING {
        @Override
        public void doThing() {
            System.out.println("One thing");
        }
    },
    OTHER_THING;
    // Default.
    @Override
    public void doThing() {
        System.out.println("No thing");
    }
}
public void doAThing(CanThing thing) {
    thing.doThing();
}
public void test(String[] args) {
    for (CanThing t: Validate.values()) {
        doAThing(t);
    }
}
 
    
    
        MC Emperor
        
- 22,334
- 15
- 80
- 130
 
    
    
        OldCurmudgeon
        
- 64,482
- 16
- 119
- 213
