【发布时间】:2024-04-15 10:05:02
【问题描述】:
如果枚举常量本质上是静态的,那么它如何成为对象和访问方法并具有构造函数。
枚举常量怎么可能是对象又是静态的呢
请参考以下代码:-
enum Apple {
Jonathan(10), GoldenDel(9), RedDel, Winesap(15), Cortland(8);
private int price; // price of each apple
// Constructor
Apple(int p) {
System.out.println("Price: " + p);
price = p;
}
// default constructor, constructor overloading
Apple() {
price = -1;
System.out.println("Price: " + price);
}
int getPrice() { return price; }
}
class EnumDemo3 {
public static void main(String args[]) {
Apple ap;
// Display price of Winesap.
System.out.println("Winesap costs " + Apple.Winesap.getPrice() + " cents.\n");
// Display all apples and prices.
System.out.println("All apple prices:");
for(Apple a : Apple.values())
System.out.println(a + " costs " + a.getPrice() + " cents.");
}
}
【问题讨论】:
-
“有一个构造函数”是什么意思?它们没有构造函数。
-
有什么问题?你能指望什么?你的代码是如何工作的?你的代码在哪一行失败了?
-
我不明白枚举常量如何可以是静态对象并且可以具有非静态成员。
-
@MiguelGarnachoVélez 他们确实有私有构造函数
标签: java methods enums static enumeration