• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Enums Doubts

 
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
i have 2 doubts regarding enums...

<blockquote>code:
<pre name="code" class="core">enum Drinks {
COFFEE("hot", 10.0), TEA("hot", 5.0), JUICE("cold", 20.0), LASSI(8.0);
String state;
double price;
private Drinks(String s, double p) {
state = s;
price = p;
}
private Drinks(double p) {
price = p;
}

}

class EnumThree {
public static void main(String[] args) {
Drinks.LASSI
// why does this statement invoke the constructors for all the 4 instances COFFEE, TEA, JUICE & LASSI?
}
}
</pre>
</blockquote>
Secondly, for enums the construtors are private(or default) then how can we instantiate in another class?

The code is modified by me.
 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
think of ENUM as a class having its constants declared in the following way (your example enum Drinks):
public static final Drinks COFFEE;
public static final Drinks TEA;
public static final Drinks JUICE;
public static final Drinks LASSI;

All four constructors are invoked because above members are initialized in a static initialization block (meaning that they are initialized when the class is first loaded):
static
{
COFFEE = new Drinks("COFFEE", 0, "hot", 10D);
TEA = new Drinks("TEA", 1, "hot", 5D);
JUICE = new Drinks("JUICE", 2, "cold", 20D);
LASSI = new Drinks("LASSI", 3, 8D);
$VALUES = (new Drinks[] {
COFFEE, TEA, JUICE, LASSI
});
}

By the way, you should have the following in the main method:
Drinks dr = Drinks.LASSI;
Otherwise you get compiler eror.

Moreover, you cannot invoke an ENUM constructor directly, it is invoked automatically, as I presented above.

Hope this helps.
[ July 17, 2008: Message edited by: Jarek Jankowski ]
 
Milan Sutaria
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Jarek. it did help me.
 
Curse your sudden but inevitable betrayal! And this tiny ad too!
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic