java enum constructor code example

Example 1: Enums injava

public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY 
}

Example 2: java enum

public class DaysOfTheWeek {

    public enum Days {m, t, w, r, f, sat, s};
  	    public static void main(String[] args) {
          Days d = Days.t; 
          System.out.println(d);
          //the output would be t
        }
}

Example 3: Enums injava

public class EnumTest {
    Day day;
    
    public EnumTest(Day day) {
        this.day = day;
    }
    
    public void tellItLikeItIs() {
        switch (day) {
            case MONDAY:
                System.out.println("Mondays are bad.");
                break;
                    
            case FRIDAY:
                System.out.println("Fridays are better.");
                break;
                         
            case SATURDAY: case SUNDAY:
                System.out.println("Weekends are best.");
                break;
                        
            default:
                System.out.println("Midweek days are so-so.");
                break;
        }
    }
    
    public static void main(String[] args) {
        EnumTest firstDay = new EnumTest(Day.MONDAY);
        firstDay.tellItLikeItIs();
        EnumTest thirdDay = new EnumTest(Day.WEDNESDAY);
        thirdDay.tellItLikeItIs();
        EnumTest fifthDay = new EnumTest(Day.FRIDAY);
        fifthDay.tellItLikeItIs();
        EnumTest sixthDay = new EnumTest(Day.SATURDAY);
        sixthDay.tellItLikeItIs();
        EnumTest seventhDay = new EnumTest(Day.SUNDAY);
        seventhDay.tellItLikeItIs();
    }
}

Example 4: java add constructor to enum

package cakes;

public class EnumDemo {

	public enum Food {
		HAMBURGER(7), FRIES(2), HOTDOG(3), ARTICHOKE(4);

		Food(int price) {
			this.price = price;
		}

		private final int price;

		public int getPrice() {
			return price;
		}
	}

	public static void main(String[] args) {
		for (Food f : Food.values()) {
			System.out.print("Food: " + f + ", ");

			if (f.getPrice() >= 4) {
				System.out.print("Expensive, ");
			} else {
				System.out.print("Affordable, ");
			}

			switch (f) {
			case HAMBURGER:
				System.out.println("Tasty");
				continue;
			case ARTICHOKE:
				System.out.println("Delicious");
				continue;
			default:
				System.out.println("OK");
			}
		}

	}

}

Tags:

Java Example