//枚举类
public enum Size{SMALL,MEDIUM,LARGE,EXTRA_LARGE};
public static void main(String[] args) {
//for循环遍历枚举类型的所有实例
for(Size s:Size.values()){
System.out.println(s);
}
}
栗子1
public class Main {
public enum Operation{
ADD{
public int eval(int arg1,int arg2){
return arg1+arg2;
}
},
SUBTRACT{
public int eval(int agr1,int arg2){
return agr1-arg2;
}
},
MULTIPLY{
public int eval(int arg1,int arg2){
return arg1*arg2;
}
},
DIVIDE{
public int eval(int arg1,int arg2){
return arg1/arg2;
}
};
//定义抽象方法
public abstract int eval(int arg1,int arg2);
}
public static void main(String[] args) {
Operation operation = Operation.ADD;
//自动寻找子类的实现
int m = operation.eval(12,13);
System.out.println(m);
}
}
栗子2
package com.tech.Apple;
import jdk.nashorn.internal.ir.CallNode;
import javax.sound.midi.Soundbank;
public class Main {
enum Operation{ADD,SUBTRACT,MULTIPLY,DIVIDE};
public static int eval(Operation op,int agr1,int arg2){
int result = 0;
switch (op){
case ADD:
return result = agr1 + arg2;
case SUBTRACT:
return result = agr1-arg2;
case MULTIPLY:
return result = agr1*arg2;
case DIVIDE:
return result = agr1/arg2;
}
return result;
}
public static void main(String[] args) {
int add_num = eval(Operation.ADD,12,13);
System.out.println(add_num);
}
}