Java的枚举类型应用

package myday01.enumeration;

import org.junit.Test;

public class Demo2 {
	public void infoOfPlanet(Planet p){
		System.out.println(p + ":mass is " + p.getMass() + "; radius is " + p.getRadius() +"; surface gravity is " + p.getSurfaceGravity() );
	}
	
	@Test
	public void test1(){
		infoOfPlanet(Planet.MERCURY);
		infoOfPlanet(Planet.VENUS);
		infoOfPlanet(Planet.EARTH);
		infoOfPlanet(Planet.JUPITER);
		infoOfPlanet(Planet.SATURN);
		infoOfPlanet(Planet.URANUS);
		infoOfPlanet(Planet.NEPTUNE);
	}
}

enum Planet{
	MERCURY(3.302e+23,2.439e6),
	VENUS  (4.869e+24, 6.052e6),  
    EARTH  (5.975e+24, 6.378e6),  
    MARS   (6.419e+23, 3.393e6),  
    JUPITER(1.899e+27, 7.149e7),  
    SATURN (5.685e+26, 6.027e7),  
    URANUS (8.683e+25, 2.556e7),  
    NEPTUNE(1.024e+26, 2.477e7);
	
	private final double mass; //in kilograms
	private final double radius;  //In meters
	private final double surfaceGravity;  //In m/s^2
	//Universal gravitational constant 
	private static final double G = 6.67300E-11;
	
	//Constructor
	Planet(double mass, double radius){
		this.mass = mass;
		this.radius = radius;
		this.surfaceGravity = G*mass/(radius * radius);
	}
	
	public double getMass(){
		return this.mass;
	}
	
	public double getRadius(){
		return this.radius;
	}
	
	public double getSurfaceGravity(){
		return this.surfaceGravity;
	}
}

//bad operation Enum example
enum BadOperation{
	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("Unknown operation:" + this);
	}
}

//good operation Enum example
enum GoodOperation {  
    GPLUS("+") {  
    double apply(double x, double y) { return x + y; }  
    },  
    GMINUS("-") {  
    double apply(double x, double y) { return x - y; }  
    },  
    GTIMES("*") {  
    double apply(double x, double y) { return x * y; }  
    },  
    GDIVIDE("/") {  
    double apply(double x, double y) { return x / y; }  
    };  
    
	
	private GoodOperation(String symbol) {
		
	}
	abstract double apply(double x, double y);
}  


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值