Enum types are not extensible, but the interface types are extensible. Using an interface, you can simulate a scalable enumeration.
As a simple calculator:
Implement interface operation, there is only one apply method.
Public Interface operation { double apply (doubledouble y);}
Basic operations:
Public enumBasicoperationImplementsOperation {PLUS ("+") { Public DoubleApplyDoubleXDoubleY) {returnX +y;} }, minus ("-") { Public DoubleApplyDoubleXDoubleY) {returnX-y;} }, Times ("*") { Public DoubleApplyDoubleXDoubleY) {returnX-y;} }, DIVIDE ("/") { Public DoubleApplyDoubleXDoubleY) {returnX-y;} }; Private FinalString symbol; Basicoperation (String symbol) { This. symbol =symbol; } PublicString toString () {returnsymbol; } }
Expand the calculator:
Public enumExtendedoperationImplementsOperation {EXP ("^") { Public DoubleApplyDoubleXDoubleY) {returnMath.pow (x, y);} }, Remainder ("%") { Public DoubleApplyDoubleXDoubleY) {returnX%y;} }; Private FinalString symbol; Privateextendedoperation (String symbol) { This. symbol =symbol; } PublicString toString () {returnsymbol; }}
Use:
Public classMain {Private Static<textendsEnum<t> & Operation>voidTest (class<t> Opset,DoubleXDoubley) { for(Operation Op:opSet.getEnumConstants ()) System.out.printf ("%f%s%f =%f%n", X, op, y, op.apply (x, y)); } Public Static voidMain (string[] args) {Doublex = 2.0; Doubley = 4.0; Test (extendedoperation.class, x, y); }}
The interface simulates the lack of a scalable enumeration: it is not possible to inherit from one enumeration to another, so some common functions are duplicated in each enumeration class. If the public has much more functionality, encapsulate it in a helper class or static helper method to avoid copying the code.
34th: Simulating a scalable enumeration with an interface