之前就学习过枚举,但因使用不多,就忘记的七七八八,为了巩固枚举的用法,就做一下笔记。
枚举类型是指由一组固定的常量组成合法值的类型
public enum Operation {
PULS,MINUS,TIMES,DIVIDE;
}
枚举没有公有构造方法,因此不能实例化对象,以“ 类名. 常量”调用。
覆写toString方法
public enum Operation {
PULS(2.0,4.4);
Operation(double x,double y){
this.param1=x;
this.param2=y;
this.result=x+y;
}
private double param1;
private double param2;
private double result;
@Override
public String toString() {
return "Operation{" +
"result=" + result +
'}';
}
}
public static void main(String[] args){
System.out.println(Operation.PULS.toString());
}
枚举类型中的抽象方法必须被它的所有常量中具体方法所覆盖。
public enum Operation {
PULS {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);
}
public static void main(String[] args){
System.out.println(Operation.PULS.apply(4,2));
}