Thursday, February 3, 2011

Java Complex Enum

So this is a very complex Enum that has another Enum inside of itself. This could be a common pattern where the Main set of Objects is dependant on the input to the Main object. This nice because Enums have the same benefits of a Class.


private enum PayrollDay {

  MONDAY(PayType.WEEKDAY);
  

  private final PayType type;

  private PayrollDay(PayType type) {
    this.type = type;
  }

  double pay(double hoursRate, double payRate) {
    return type.pay(hoursRate, payRate);
  }

  enum PayType {

    WEEKDAY {

      double overtimePay(double hoursRate, double payRate) {
        return hoursRate <= 8 ? 0 : hoursRate * payRate / 2; 

      }
  }; 

  abstract double overtimePay(double hoursRate, double payRate); 

  private double pay(double hoursRate, double payRate) { 
    double basePay = hoursRate * payRate; 
    double overtime = overtimePay(hoursRate, payRate); 
    return basePay + overtime; 
  }

Java Enums Fun

As I am studying for the SCJP certification for Java I am going to mention some things in the next few months regarding Java Programming.

Currently Reading about ENUMS

So you can create an enum with a constructor.

  • This is implicitly private.
  • Java will only compile with default and private access modifier.


public enum Cup {

SMALL(4), LARGE(8), HUGE(16);
private final int size;

private Cup(int size) {
this.size = size;
}

public int size() {
return size;
}
}

public enum Plate {

SMALL(4), LARGE(8), HUGE(16);
private final int size;

Plate(int size) {
this.size = size;
}

int size() {
return size;
}
}



Notice the private Cup(int size) constructor and the Plate(int size) constructor. Both of these mean private constructor.