我正在看书中提供的示例代码
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());
}
}
如果枚举就像一个类,是否可以像在此使用denomValue那样在类中为方法和字段使用相同的名称?
为什么以这种方式调用
int numQuarters = Coin.QUARTER.toDenomination(numPennies);
?默认情况下toDenomination()
是静态的吗?在上述情况下,denomValue字段的值是多少?该程序的输出暗示它应该等于QUARTER。但是,如何运作? Coin.QUARTER是否等效于创建硬币对象并将QUARTER作为构造函数参数传递?
最佳答案
每个PENNY
,NICKEL
都是Coin
类的实例,并且是静态的,因此可以作为Coin.PENNY
进行访问。
因此,当您这样做时:
Coin.QUARTER.toDenomination(numPennies)
您正在访问硬币类的
QUARTER
实例并调用其toDenomination()
方法,该方法是在QUARTER
实例上调用的实例方法。当您这样做时:
PENNY(1) //this actually calls the constructor with one integer argument of Coin class
要检查PENNY是
Coin
类的实例:System.out.println(Coin.PENNY.getClass()); //Will show you Coin