3 回答
TA贡献1847条经验 获得超11个赞
你可以有这样的东西
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();
}
TA贡献1951条经验 获得超3个赞
通常你可以使用类类型,而不是枚举类型。枚举旨在是静态的和最终的。枚举构造函数的想法是封装几个值,以便您可以通过仅设置一种类型的枚举来使用它们。
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("-----------------");
}
}
}
TA贡献1829条经验 获得超7个赞
您可能知道 - 枚举类型的构造函数必须是包私有或私有访问。
它被自动调用并创建在枚举体开头定义的常量。
您不能自己调用枚举构造函数。
以下是一些可能有用的示例。
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
}
添加回答
举报