Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

override abstract enum method

Tags:

enums

groovy

The following is valid Java code:

enum ProductType {
  CASH_BONUS { 

     void doSomething() {}    
  },

  CUSTOMIZABLE { 
     void doSomething() {}    
  }

  abstract void doSomething()
}

But when I try to run this in the Groovy console, I get the errors:

Can't have an abstract method in a non-abstract class. The class 'ProductType' must be declared abstract or the method 'void doSomething()' must be implemented. at line: -1, column: -1

Can't have an abstract method in a non-abstract class. The class 'ProductType' must be declared abstract or the method 'void doSomething()' must not be abstract. at line: 11, column: 3

I seem to recall reading that Groovy does not (yet) support overriding methods for enum constants, is this correct, and if so, is there an elegant way to emulate this behavior?

Update

This was a bug that was fixed some time around Groovy 1.8.0

like image 582
Dónal Avatar asked Oct 10 '22 23:10

Dónal


1 Answers

it's a bug: http://jira.codehaus.org/browse/GROOVY-4641

you can make the abstract method not abstract. throw an exception to make sure you always override it like:

enum ProductType {
    CASH_BONUS(1) {
        void doSomething() {
        }
    },
    CUSTOMIZABLE(2) {
        void doSomething() {
        }
    };
    ProductType(int n) {
        this.n=n;
    }
    final int n;
    void doSomething() {
        throw new UnsupportedOperationException()
    }
}

ProductType.CASH_BONUS.doSomething();
ProductType.CUSTOMIZABLE.doSomething();
like image 136
Ray Tayek Avatar answered Nov 17 '22 08:11

Ray Tayek