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);
}
Java的枚举类型应用
最新推荐文章于 2024-06-29 08:45:00 发布