Win a copy of Murach's Java Programming this week in the Beginning Java forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

confusion regardind enum and constructors  RSS feed

 
kapilg gupta
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
enum Coffesize
{
BIG(8),HUGE(10)

Coffeesize (int ounces)
{
this.ounces=ounces;
}
private in ounces;
public int getounces()
{
return ounces;
}
}
class Coffee
{
Coffesize size;
public Staic...........................
Coffe drink1=new Coffee();
drink1.size=Cofeesize.BIG;//this statement calls the constructor altough
integer is not passed how
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 15985
86
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You never call the destructor of an enum explicitly.

An enum is a kind of class, of which only a fixed number of instances exist: the constants that you defined in the enum. So in your case, there are two instances, referred to by BIG and HUGE.

You can re-write an enum as a regular class; maybe this will help you to understand what happens. It looks more or less like this:
 
Campbell Ritchie
Marshal
Posts: 54878
155
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But it doesn't work. You are not calling its constructor, but its "ounces" attribute, which you have quite correctly given private access. Your app won't compile.
You can read all about enums here in the Java tutorial.

CR
 
I'm THIS CLOSE to ruling the world! Right after reading this tiny ad:
Thoughts on deprecation in Java
https://coderanch.com/t/683016/java/Deprecation-Java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!