Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

How are enum constructors initialised  RSS feed

 
Vishal Hegde
Ranch Hand
Posts: 1078
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
Saloon Keeper
Posts: 3998
42
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: 1078
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
Sheriff
Posts: 16028
87
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: 1078
Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
then are enum constructors private???
 
Campbell Ritchie
Marshal
Posts: 55751
163
  • 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
Marshal
Posts: 55751
163
  • 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
Posts: 21092
85
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
Boost this thread!