This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Enum Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Enum" Watch "Enum" New topic
Author

Enum

Gaurav Pavan Kumar Jain
Ranch Hand

Joined: Mar 19, 2007
Posts: 168
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

Joined: Feb 28, 2007
Posts: 1707
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 ]

cmbhatt
m ali
Ranch Hand

Joined: Apr 12, 2007
Posts: 49
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

Joined: Feb 28, 2007
Posts: 1707
Hi Ali,

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



Regards,
cmbhatt
m ali
Ranch Hand

Joined: Apr 12, 2007
Posts: 49
Thank you Chandra, I got it.
Omer Haderi
Ranch Hand

Joined: Sep 27, 2006
Posts: 42


in the initial code:
it seems that you re-assign the same object...
Gaurav Pavan Kumar Jain
Ranch Hand

Joined: Mar 19, 2007
Posts: 168
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

Joined: Feb 28, 2007
Posts: 1707
Gaurav,

 
wood burning stoves
 
subject: Enum
 
Similar Threads
confusion regardind enum and constructors
Enum programs are not compiling in java5.0 compiler?
Enums...
use of " this " ...
Doubt regarding enum