我需要了解java中的枚举行为吗? [英] I need to understand behaviour of enum in java example?
问题描述
第一个是枚举类
enum coffeeSize{
BIG(8), HUGE(10), OVERWHELMING(16);
private int ounces;
coffeeSize(int ounces ){
this.ounces = ounces;
}
public int getOunces(){
return ounces;
}
}
这是Class CoffeeTest1和main
This is class CoffeeTest1 and main
public class CoffeeTest1 {
coffeeSize size;
public static void main (String args[]) {
CoffeeTest1 drink1 = new CoffeeTest1();
drink1.size = coffeeSize.BIG;
System.out.println(" " + drink1.size.getOunces());
}
}
以下是输出
8
我的问题:
我不明白如何 drink1.size.getounces()
管理输出8.我没有给出构造函数 coffeeSize( 8)
object(例如: coffeeSize somex = new coffeeSize(BIG)
)。我想知道这个简单的微妙逻辑背后。有人可以帮我理解吗?
My question :
I don't understand the how drink1.size.getounces()
manage to output 8. I haven't given constructor coffeeSize(8)
object (ex: coffeeSize somex = new coffeeSize(BIG)
). I want to know this simple subtle logic behind. Can someone help me understand please?
推荐答案
我不明白drink1.size.getounces()管理输出8。
I dont understand the how "drink1.size.getounces() " manage to output 8.
[...]
我想知道这个简单的微妙逻辑。
I want to know this simple subtle logic behind.
为了理解这个背后的逻辑,你可以将枚举
作为一个常规的类
(这是实际上如何编译)和
To understand the logic behind this, you can think of your enum
as a regular class
(which is actually how it is compiled), and
BIG(8)
作为类的一个实例类似于
as an instance of this class similar to
new coffeesize(8);
现在应该清楚为什么 drink1.size.getOunces() code> print 8:
BIG
只是 coffeesize
枚举的一个实例,您为此设置盎司
构建时为8。
It should now be clear why drink1.size.getOunces()
prints 8: BIG
is just an instance of the coffeesize
enum, for which you set ounces
to 8 when constructing it.
这篇关于我需要了解java中的枚举行为吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!