Enum Example – Ebook Effective Java 2nd


Example 1 : We create Enum with two parameters and interract with member in Enum

Enum Planet

package thaihoanghai.enums;

public 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; // kilogram
	private final double radius; // meters
	private final double surfaceGravity; // m/s^2 (Lực hấp dẫn)

	private static final double G = 6.67300E-11; // hằng số hấp dẫn

	private Planet(double mass,double radius) {
		this.mass = mass;
		this.radius = radius;
		surfaceGravity = G * mass / Math.pow(radius, 2);
	}

	public double getMass() {
		return mass;
	}

	public double getRadius() {
		return radius;
	}

	public double getSerfaceGravity() {
		return surfaceGravity;
	}

	public double surfaceWeight(double mass){ // trọng lượng bề mặt
		return mass * surfaceGravity; // F = ma
	}

}

Test Main PlanetMain.java

package thaihoanghai.enums;

public class PlanetTest {
	public static void main(String[] args) {
		double earthWeight = 100000;
		double mass = earthWeight / Planet.EARTH.getSerfaceGravity();
		for(Planet p : Planet.values()){
			String result = String.format("Weight on %s is %.2f", p,p.surfaceWeight(mass));
			System.out.println(result);			
		}
	}
}

 

Result :

d1

 

Example 2 : We create Enum Operation for work basic calculations.

Enum Operation

package thaihoanghai.enums;

import java.util.HashMap;
import java.util.Map;

// Enum type that switches on its own value
public enum Operation {
	// Fix Problem.
	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;}};

	abstract double apply(double x, double y);

	private final String symboy;
	Operation(String symboy){
		this.symboy = symboy;
	}

	@Override
	public String toString() {
		return this.symboy;
	}
	// implementing a fromString method on an enum type
	private static final Map<String, Operation> stringToEnum = 
			new HashMap<String,Operation>();
	static{ // Initialize map from constant name to enum constant
		for(Operation op : values()){
			stringToEnum.put(op.toString(), op);
		}
	}
	// return operation for string, or null if string is invalid
	public static Operation fromString(String symbol){
		return stringToEnum.get(symbol);
	}

	/* Ok, is not good . Because when we add new operation . If we don't add into switch-case => Throw exception
	PLUS, MINUS, TIMES, DIVIDE;
	// do the arithmetic op represented by this constant
	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);
	}
	*/

}

OperationMain.java for Test

package thaihoanghai.enums;
public class OperationTest {
	public static void main(String[] args) {
		double x = 1000;
		double y = 2500;

		for(Operation op : Operation.values()){
			System.out.println(String.format("%.2f %s %.2f = %.2f%n", x,op,y,op.apply(x, y)));
		}
		//===================================================================================
		Operation myOperation = Operation.fromString("+");
		if(myOperation != null)
			System.out.println("Result PLUS 10 + 10 = " + myOperation.apply(10, 10));
		else
			System.out.println("Operation is invalid...");
	}
}

Result :
d1

Example 3 : We create Enum PayrollDay for work Payroll day work in week .

package thaihoanghai.enums;

public enum PayrollDay {
	MONDAY(PayType.WEEKDAY),	TUESDAY(PayType.WEEKDAY),
	WEDNESDAY(PayType.WEEKDAY), THURSDAY(PayType.WEEKDAY),
	FRIDAY(PayType.WEEKDAY),

	SATURDAY(PayType.WEEKDAY),	SUNDAY(PayType.WEEKDAY);

	private final PayType payType;
	PayrollDay(PayType payType) {
		this.payType = payType;
	}

	double pay(double hoursWorked, double payRate){
		return payType.pay(hoursWorked, payRate);
	}

	// the strategy enum type
	private enum PayType{
		WEEKDAY{
			@Override
			double overtimePay(double hours, double payRate) {				
				return hours <= HOURS_PER_SHIFT ? 0 : (hours - HOURS_PER_SHIFT) * payRate / 2;
			}
		},
		WEEKEND{
			@Override
			double overtimePay(double hours, double payRate) {				
				return hours * payRate / 2;
			}			
		};

		private static final int HOURS_PER_SHIFT = 8;
		abstract double overtimePay(double hours, double payRate);
		double pay(double hoursWorked, double payRate){
			double basePay = hoursWorked * payRate;
			return basePay + overtimePay(hoursWorked, payRate);
		}
	}
}

PayrollDayTest.java

package thaihoanghai.enums;

public class PayrollDayTest {
	public static void main(String[] args) {
		double money1 = PayrollDay.MONDAY.pay(10, 20);
		double money2 = PayrollDay.SUNDAY.pay(50, 100);
		System.out.println("$"+money1);
		System.out.println("$"+money2);
	}
}

Result :

d1

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: