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

How are enum constructors initialised

 
Vishal Hegde
Ranch Hand
Posts: 1077
Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
are enums constructors intialised automatically without the creation of objects

example: enum Coffee
{
BIG(10),MEDIUM(20),LARGE(30);
Coffee(int ounces)
{
this.ounces=ounces;
}
private int ounces;
 
Vijitha Kumara
Bartender
Posts: 3914
9
Chrome Fedora Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Vishal Hegde wrote:are enums constructors intialised automatically without the creation of objects

Enum has a consructor which will be invoked by the enum declaration in your code (programmers cannot invoke it).
 
Vishal Hegde
Ranch Hand
Posts: 1077
Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ok are enum constructors private or can it contain all the access modifier
 
Hariharan Ram Kumar
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Enum constructors can contain any modifiers.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Pie
Posts: 15438
41
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hariharan Ram Kumar wrote:Enum constructors can contain any modifiers.

No they can't. Did you try it out? If you try making the constructor of an enum public or protected, you'll get a compiler error.
 
Vishal Hegde
Ranch Hand
Posts: 1077
Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
then are enum constructors private???
 
Campbell Ritchie
Sheriff
Pie
Posts: 49776
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Vishal Hegde wrote:then are enum constructors private???
As far as I know, yes. In the Java Language Specification it doesn't say a lot about enum constructors, only that a default enum constructor is private.
 
Satya Maheshwari
Ranch Hand
Posts: 368
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Could you tell the use case for invoking enum construtors?
One way of looking enum is like a set of known constants. Hence I am curious to know the use case of 'constructing constants'.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49776
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Like most things, there is something useful in the Java™ Tutorials.
 
Rob Spoor
Sheriff
Pie
Posts: 20608
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try the following:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic