In this example, we will show a custom constructor in an enumeration with private definition.
Source Code
1.enum)
package com.beginner.examples;
public enum Week {
MON(1), TUE(2), WED(3), THRUS(4), FIR(5), STA(6), SUN(7);
private int num;
// The default constructor in the enumeration is private,
// and defining a public constructor will cause an error
private Week(int num) {
this.num = num;
}
@Override
// Override the toString() method in order to be able to return the attribute
// value num
public String toString() {
return this.name() + " : " + this.num;
}
}
2)
package com.beginner.examples;
public class EnumCustomConstructor {
public static void main(String[] args) {
// Use custom enumerations
Week w1 = Week.MON;
Week w2 = Week.TUE;
Week w3 = Week.WED;
System.out.println(w1);
System.out.println(w2);
System.out.println(w3);
}
}
Output:
MON : 1
TUE : 2
WED : 3