实现方式一:
public enum Operation { PLUS, MINUS, TIMES, DIVIDE; double apply(double x, double y) { switch (this) { case PLUS: return x + y; case MINUS: return x - y; case TIMES: return x * y; case DIVIDE: return x / y; } throw new AssertionError("Unknow op:" + this); } }
实现方式二:
特定于常量的方法实现(constant-specific method implementation)
public enum Operation { PLUS { double apply(double x, double y) { return x + y; } }, MINUS { double apply(double x, double y) { return x - y; } }, TIMES { double apply(double x, double y) { return x * y; } }, DIVIDE { double apply(double x, double y) { return x / y; } }; abstract double apply(double x, double y); }
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/15951.html