Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Enum

 
Gaurav Pavan Kumar Jain
Ranch Hand
Posts: 168
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Folks

Please help me to understand the meaning of line //1 and line //2 in the following code.

enum CoffeeSize
{
BIG(8), HUGE(10),OVERWHELMING(16);
}

CoffeeSize(int ounce)
{
this.ounce=ounce;
}

private int ounce;
public int getounce()
{
return ounce;
}
}

class Coffee
{
CoffeeSize size; //1

public static void main(String args[])
{
Coffee drink=new Coffee();
drink.size=CoffeeSize.BIG; //2

Coffee drink1=new Coffee();
drink.size= CoffeeSize.OVERWHELMING;

System.out.println(drink.size.getounce());
System.out.println(drink1.size.getounce());
}
}

 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Gaurav,

Your code gives compiler error due following:
1- extra parenthesis after
BIG(8), HUGE(10),OVERWHELMING(16);


Modified code:



static CoffeeSize size; //1
In the class Coffee, you have an enum CoffeeSize that is instance variable
of class Coffee.



Coffee drink=new Coffee();
drink.size=CoffeeSize.BIG; //2

You created an instance of your class in the main method and assigned
constant CoffeeSize.BIG to drink.size (member variable of Object drink)
CoffeeSize.BIG is enum constant, that can only be assigned to enum type object.




Regards,
cmbhatt
[ April 16, 2007: Message edited by: Chandra Bhatt ]
 
m ali
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Chandra,

Can anybody explain me, why the output is differ in the following two situations.

1)

The output is: 16 16


2)

The output is: 10 16

Thanks in Advance.
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ali,

Recheck your output.
Nothing like what you say.
Output will be same...



Regards,
cmbhatt
 
m ali
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Chandra, I got it.
 
Omer Haderi
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


in the initial code:
it seems that you re-assign the same object...
 
Gaurav Pavan Kumar Jain
Ranch Hand
Posts: 168
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Folks for your help but I also wants to know that what the "size" denoting in the code(at //1).



[ April 16, 2007: Message edited by: Gaurav Pavan Kumar Jain ]
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Gaurav,

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic