1 package com.twoslow.cha6;2 3 public interface OperationInterface {4 5 double apply(double x , double y) ;6 }
1 package com.twoslow.cha6; 2 3 public enum BaseOperation implements OperationInterface{ 4 5 PLUS("+"){ 6 public double apply(double x , double y ) {return x + y ;} 7 }, 8 MINUS("-"){ 9 public double apply(double x , double y ) {return x - y ;}10 },11 TIMES("*"){12 public double apply(double x , double y ) {return x * y ;}13 },14 DIVIDE("/"){15 public double apply(double x , double y ) {return x / y ;}16 } ;17 18 private final String symbol ;19 20 BaseOperation(String symbol) {21 this.symbol = symbol ;22 }23 }
1 package com.twoslow.cha6; 2 3 public enum ExtendedOperation implements OperationInterface{ 4 5 EXP("^") { 6 public double apply(double x, double y){return Math.pow(x, y) ;}; 7 } , 8 9 REMAINDER("%") {10 public double apply(double x , double y ) {return x % y ;} ;11 } ;12 13 14 private final String symbol ;15 16 ExtendedOperation(String symbol) {17 this.symbol = symbol ;18 }19 }
1 package COM. twoslow. cha6; 2 3 Import Java. util. arrays; 4 Import Java. util. collection; 5 6 public class maintest {7 8 public static void main (string [] ARGs) {9 // test (extendedoperation. class, 3, 2); 10 11 Test2 (arrays. aslist (baseoperation. values (), 3, 2 ); 12} 13 14 // The generic declaration ensures that the object represents both enumeration and operation subtype 15 private static <t extends Enum <t> & operationinterface> void test (class <t> opset, double X, doub Le y) {16 for (operationinterface OP: opset. getenumconstants () {17 system. out. println (op. apply (x, y); 18} 19} 20 21 Private Static void Test2 (collection <? Extends operationinterface> opset, double X, Double Y) {22 for (operationinterface OP: opset) {23 system. out. println (op. apply (x, y); 24} 25} 26}
Chapter 6: enumeration and annotation. Item34: use interfaces to simulate scalable enumeration.