The first one is enum class
enum coffeeSize{
BIG(8), HUGE(10), OVERWHELMING(16);
private int ounces;
coffeeSize(int ounces ){
this.ounces = ounces;
}
public int getOunces(){
return ounces;
}
}
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());
}
}
The below is output
8
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?
To understand the logic behind this, you can think of your
enumas a regularclass(which is actually how it is compiled), andas an instance of this class similar to
It should now be clear why
drink1.size.getOunces()prints 8:BIGis just an instance of thecoffeesizeenum, for which you setouncesto 8 when constructing it.