带构造方法的枚举
package com.howlaa.day03; public class EnumTest { public static void main(String[] args) { WeekDay weekday =WeekDay.FRI; System.out.println(weekday); System.out.println(weekday.name()); System.out.println(weekday.ordinal()); System.out.println(weekday.valueOf("SUN")); System.out.println(weekday.values().length); } public enum WeekDay{ SUN(1),MON(),TUE,WED,THI,FRI,SAT; private WeekDay(){ System.out.println("first"); } private WeekDay(int day){ System.out.println("second"); } } }
输出结果:
注意:构造方法要写在静态变量后面。构造方法要设为private。原因是如果是public,别人可以调用,也失去了枚举的意义。
在静态变量后加小括号表示要调用哪个构造方法。