effective java——30使用enum
阿新 • • 發佈:2018-12-26
1,
列舉太陽系八大行星
package com.enum30.www; public enum Planet {//列舉太陽系八大行星 MERCURY(3.302e+23,2.439e6), VENUS(4.8e+24,6.0e6), EARTH(5.9e+24,6.3e6); private final double mass; //kilogram private final double radius; //meters private final double surfaceGravity; //In m/s^2 privatestatic final double G=6.67E-11; //consrtuctor Planet(double mass, double radius) { this.mass = mass; this.radius = radius; surfaceGravity=G*mass/(radius*radius); } public double surfaceWeight(double mass){ return mass*surfaceGravity; //F=ma } publicdouble getMass() { return mass; } public double getRadius() { return radius; } public double getSurfaceGravity() { return surfaceGravity; } public static void main(String[] args) { if (args.length != 1) { System.err.println("Usage: java Planet <earth_weight>"); System.exit(-1); } double earthWeight=Double.parseDouble(args[0]); double mass=earthWeight/Planet.EARTH.getSurfaceGravity(); for(Planet p:Planet.values()){ System.out.printf("Weight on %s is %f%n", p, p.surfaceWeight(mass)); } } }
2.使用更為簡潔的方式表達+ - * /
package com.enum30demo2.www; import com.sun.org.apache.xpath.internal.operations.Minus; 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; }}, DEVIDE{double apply(double x,double y){ return x/y; }}; abstract double apply(double x,double y); }View Code
3.使用更為安全的方式來執行工資計算,增大可讀性,降低出錯率
package com; public enum PayrollDay { MONDAY(PayType.WEEKDAY),TUESDAY(PayType.WEEKDAY), WEDNESDAY(PayType.WEEKDAY),THURSDAY(PayType.WEEKDAY), FRIDAY(PayType.WEEKDAY),SATURDAY(PayType.WEEKEND), SUNDAY(PayType.WEEKEND); private PayType payType; PayrollDay(PayType payType) { this.payType=payType; } double pay(double homeWork,double payRate){ return payType.pay(homeWork,payRate); } private enum PayType{ WEEKDAY{ double overtimePay(double hours,double payRate){ return hours<=HOURS_PER_SHIFT? 0:(hours-HOURS_PER_SHIFT)*payRate; } }, WEEKEND{ double overtimePay(double hours,double payRate){ return hours*payRate; } }; private final static int HOURS_PER_SHIFT=8; abstract double overtimePay(double hrs,double payRate); double pay(double homeWork,double payRate){ double basePay=(homeWork-HOURS_PER_SHIFT)*payRate; return basePay+overtimePay(homeWork,payRate); } } public static void main(String[] args) { double hours=8.8; double payRate=20.0; double total=MONDAY.pay(hours,payRate); System.out.println(total); } }