Java基础(11):枚举类型

枚举类型

          由常量组成的参数类型。如下:

public class EnumTest {

	@Test
	public void test() {

		for(Operation op:Operation.values()){
			System.out.printf("%s %.2f\n",op,op.apply(1,2));
		}
		
	}

	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;}};
		
		private final String symbol;
		
		Operation(String symbol){this.symbol=symbol;};
		
		public String toString(){return symbol;};
		
		abstract double apply(double x,double y);
		
	}
	
}

   枚举类型可以继承接口扩展,如下:

public class ExtendEnumTest {

	@Test
	public void test() {
		for(BasicOperation o:NormalOperation.values()){
			System.out.printf("%s %.2f\n",o,o.apply(3,2));
		}
		for(BasicOperation o:ExtendOperation.values()){
			System.out.printf("%s %.2f\n",o,o.apply(3,2));
		}
	}

	public interface BasicOperation{
		double apply(double x,double y);
	}
	public enum NormalOperation implements BasicOperation {
		
		PLUS("+"){public double apply(double x,double y){return x+y;}},
		MINUS("-"){public double apply(double x,double y){return x-y;}},
		TIMES("*"){public double apply(double x,double y){return x*y;}},
		DIVIDEE("/"){public double apply(double x,double y){return x/y;}};
		
		public String symbol;
		
		NormalOperation(String symbol){this.symbol=symbol;};
		
		@Override 
		public String toString(){
			return symbol;
		}
		
	} 
	
	public enum ExtendOperation implements BasicOperation{

		
		REMINDER("%"){public double apply(double x,double y){return x%y;}};
		
        public String symbol;
		
        ExtendOperation(String symbol){this.symbol=symbol;};
		
		@Override 
		public String toString(){
			return symbol;
		}
		
	}
	
}





阅读更多
换一批

没有更多推荐了,返回首页