public enum Operation { PLUS,MINUS,TIMES,DIVIDE;//每一个枚举值都是一个实例 double eval(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; default: return 0; } } public static void main(String[] args) { System.out.println(Operation.PLUS.eval(3,4)); System.out.println(Operation.MINUS.eval(3,4)); System.out.println(Operation.TIMES.eval(3,4)); System.out.println(Operation.DIVIDE.eval(32,4)); } }
[[email protected] java]# java Operation
7.0
-1.0
12.0
0.0
下面如果我们想使用内部类来解决呢?
public enum Operation2 { PLUS { public double eval(double x,double y) { return x + y; } },//为什么这里会有一个,号呢?看了匿名内部类,你就会明白 MINUS { public double eval(double x,double y) { return x - y; } }, TIMES { public double eval(double x ,double y) { return x * y; } }, DIVIDE { public double eval(double x,double y) { return x % y; } }; //为枚举类定义了一个抽象方法 //这个抽象方法由不同的枚举值提供不同的实现 public abstract double eval(double x,double y); public static void main(String[] args) { System.out.println(Operation2.PLUS.eval(3,4)); System.out.println(Operation2.MINUS.eval(3,4)); System.out.println(Operation2.TIMES.eval(3,4)); System.out.println(Operation2.DIVIDE.eval(3,4)); } }
时间: 2024-10-12 15:46:56