我有这个枚举单例类:
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
构造函数?
答案 0 :(得分:2)
你可以像那样吃东西
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();
}
答案 1 :(得分:1)
通常,您可以使用类类型,而不是枚举类型。枚举旨在为静态的和最终的。枚举构造函数的想法是封装多个值,以便您可以在以后只设置一种枚举类型就可以使用它们。
public enum Vehicle {
CAR(4, 2),
TRUCK(6, 20);
private Integer numOfTyres;
private Integer maxWeight;
Vehicle(Integer numOfTyres, Integer maxWeight) {
this.numOfTyres = numOfTyres;
this.maxWeight = maxWeight;
System.out.println("Number of Tyres = " + numOfTyres);
System.out.println("Max weight = " + maxWeight);
}
public Integer getMaxWeight() {
return maxWeight;
}
public Integer getNumberOfTyres() {
return numOfTyres;
}
}
public class Main {
public static void main(String s[]) {
Vehicle.CAR.getNumberOfTyres();
for (Vehicle v : Vehicle.values()) {
System.out.println();
StringBuilder sb = new StringBuilder();
sb.append("Vehicle ");
sb.append(v.name());
sb.append(" has ");
sb.append(v.getNumberOfTyres());
sb.append(" number of tyres and ");
sb.append(v.getMaxWeight());
sb.append(" max weight ");
System.out.println("-----------------");
System.out.println(sb.toString());
System.out.println("-----------------");
}
}
}
答案 2 :(得分:0)
您可能知道-枚举类型的构造函数必须是程序包私有或私有访问。
它会自动调用并创建在枚举主体开头定义的常量。
您不能自己调用枚举构造函数。
以下是一些可能有用的示例。
public enum MySingleton {
// if you have multiple constants here - it's not Singleton
INSTANCE;
// if you need to provide some info to your INSTANCE,
// you can add params to its methods
public void someMethod(String value) {
System.out.println("inside someMethod, value is " +value);
}
}
如果您需要实例具有某种状态,则可以添加字段和构造函数:
public enum MySingleton {
INSTANCE("Hello");
private String message;
MySingleton(String msg) {
this.message = msg;
}
// you can even have getter/setter for it
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
主要方法示例:
public static void main(String[] args) {
System.out.println(MySingleton.INSTANCE.getMessage()); // prints Hello
MySingleton.INSTANCE.setMessage("Bye");
System.out.println(MySingleton .INSTANCE.getMessage()); // prints Bye
}