你可能知道,有些人声明单例的枚举为 1 个实例,因为 JVM 保证总是有一个没有并发问题需要处理的单例......
那么具有多个实例的枚举呢? 我们可以说像枚举这样的东西是一种共享公共(public)接口(interface)的有序单例集吗? 为什么?
public enum EnumPriceType {
WITH_TAXES {
@Override
public float getPrice(float input) {
return input*1.20f;
}
public String getFormattedPrice(float input) {
return input*1.20f + " €";
}
},
WITHOUT_TAXES {
@Override
public float getPrice(float input) {
return input;
}
},
;
public abstract float getPrice(float input);
public static void main(String[] args) {
WITH_TAXES.getFormattedPrice(33f);
}
}
在这段代码中为什么这不起作用: WITH_TAXES.getFormattedPrice(33f); 如果不通过公共(public)接口(interface)就不能调用它,那么声明一个公共(public)方法有什么意义呢? 我想这就是为什么我没有看到任何语法能够仅为 Enum 的一个实例声明接口(interface)。
编辑:
枚举实例似乎是一种特殊的匿名类。 因此我明白为什么你不能调用那个方法。
我的问题有点相关:为什么匿名类不能实现接口(interface)(除了它可能已经实现的接口(interface)!)
我完全理解为什么我们不能这样做:
Vehicle veh = new Vehicle() {
public String getName() {
return "toto";
}
};
veh.getName();
(这里的getName不是覆盖)
我不明白的是为什么我们不能用匿名类做到这一点:
Runnable veh = new Vehicle() implements Runnable {
@Override
public void run() {
System.out.println("i run!");
}
};
veh.run();
或者会产生相同结果的东西。 想一想:如果您不使用匿名类,您完全可以扩展 Vehicle 类,然后让该子类实现您想要的任何其他接口(interface)...
我非常确定,如果可能的话,我们将能够以类型安全的方式调用 WITH_TAXES.getFormattedPrice(33f),因为 WITH_TAXES 不是真正的 EnumPriceType,而是 EnumPriceType 的子类,具有自己的接口(interface),并通过使用硬编码的 WITH_TAXES 调用 WITH_TAXES.getFormattedPrice(33f),您在编译时知道您正在调用哪个 EnumPriceType 子级。
所以我的问题是:是否有任何原因导致这不可能?或者只是还没有完成?
最佳答案
您的枚举等同于以下普通类(事实上,这几乎就是编译器将其变成的样子):
public abstract class EnumPriceType {
public static final EnumPriceType WITH_TAXES = new EnumPriceType() {
//getPrice() {...}
//getFormattedPrice() {...}
};
public static final EnumPriceType WITHOUT_TAXES = new EnumPriceType() {
//getPrice() {...}
};
public abstract float getPrice(float input);
public static void main(String[] args) {
WITH_TAXES.getFormattedPrice(33f);
}
}
getFormattedPrice()
方法在抽象类型上不可用,因此不能从 main 方法调用。考虑一下如果重写 main 方法以使用局部变量会发生什么情况:
public static void main(String[] args) {
EnumPriceType foo = EnumPriceType.WITH_TAXES;
foo.getFormattedPrice(33f);
}
这不会编译,因为 getFormattedPrice()
在基类上不可用。由于 WITH_TAXES
实例是 EnumPriceType
的匿名子类,因此您无法将局部变量定义为 getFormattedPrice ()
方法可见。
作为元观察,这是强类型语言(如 Java)和“鸭子类型”语言(如 Ruby)之间的一个关键区别。如果 getFormattedPrice()
方法恰好存在,Ruby 将愉快地调用该方法,而不管 foo
变量中保存的是什么类型的对象。
作为另一个元观察,同一 enum
的不同常量具有不同的 sets 方法没有多大意义。如果您不能将所需的一切作为抽象(或具体)方法放在基本枚举类型上,则您可能使用了错误的工具来解决问题。
关于java - 单例、枚举和匿名内部类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7599776/