在枚举单例中调用参数化构造函数?
问题描述:
我有这个枚举类:
enum C1 {
INSTANCE("");
C1(String s) {
System.out.println("with param = " +s);
}
C1() {
System.out.println("without param");
}
public void g() {
System.out.println("inside g");
}
}
public class Main {
public static void main(String s[]) {
C1.INSTANCE.g();
C1.INSTANCE.g();
}
}
我怎么称呼 C1(String s)
构造函数,使用 INSTANCE
通过传递自定义参数?
How can i call C1(String s)
constructor using INSTANCE
by passing custom parameter ?
答
您可以像这样
enum C1 {
WITH_PARAM("value"),
EMPTY();
private String value;
C1(String s) {
System.out.println("with param = " +s);
value=s;
}
C1() {
System.out.println("without param");
}
public void g() {
System.out.println("inside g, value is "+value);
}
}
public static void main(String s[]) {
C1.EMPTY.g();
C1.WITH_PARAM.g();
}