我正在查看我书中提供的示例代码
enum Coin
{
PENNY(1),
NICKEL(5),
DIME(10),
QUARTER(25);
private final int denomValue;
Coin(int denomValue)
{
this.denomValue = denomValue;
}
int denomValue()
{
return denomValue;
}
int toDenomination(int numPennies)
{
return numPennies / denomValue;
}
}
public class Coins
{
public static void main(String[] args)
{
if (args.length == 1)
{
int numPennies = Integer.parseInt(args[0]);
System.out.println(numPennies + " pennies is equivalent to:");
int numQuarters = Coin.QUARTER.toDenomination(numPennies);
System.out.println(numQuarters + " " + Coin.QUARTER.toString() +
(numQuarters != 1 ? "s," : ","));
numPennies -= numQuarters * Coin.QUARTER.denomValue();
int numDimes = Coin.DIME.toDenomination(numPennies);
System.out.println(numDimes + " " + Coin.DIME.toString() +
(numDimes != 1 ? "s, " : ","));
numPennies -= numDimes * Coin.DIME.denomValue();
int numNickels = Coin.NICKEL.toDenomination(numPennies);
System.out.println(numNickels + " " + Coin.NICKEL.toString() +
(numNickels != 1 ? "s, " : ", and"));
numPennies -= numNickels*Coin.NICKEL.denomValue();
System.out.println(numPennies + " " + Coin.PENNY.toString() +
(numPennies != 1 ? "s" : ""));
}
System.out.println();
System.out.println("Denomination values:");
for (int i = 0; i < Coin.values().length; i++)
System.out.println(Coin.values()[i].denomValue());
}
}
如果 enum 就像一个类,是否可以在类中为方法和字段使用相同的名称,就像在 denomValue 中所做的那样?
为什么会int numQuarters = Coin.QUARTER.toDenomination(numPennies);
以这种方式调用?toDenomination()
默认 是静态的吗?
在上述情况下,denomValue 字段的值是多少?该程序的输出提示它应该等于 QUARTER。但这是如何工作的?Coin.QUARTER 是否等同于创建一个硬币对象并将 QUARTER 作为其构造函数参数传递?