Java一個枚舉類的2種實現。
阿新 • • 發佈:2017-08-08
log specific 2種 方法 throw new constant per str 實現方式一:
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(doublex, double y); }
Java一個枚舉類的2種實現。