• 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

Strange behaviour of enum

 
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi! Why my code produce output "constructor, constructor", while I create only one instance of Size?

public class TestEnum {

public static void main(String[]args){
Size s=Size.BIG;
}
}

enum Size{
BIG,SMALL;

Size() {
System.out.println("constructor");
}
}
 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Andry

I may be wrong as I only studied enums for the first time last night but I think the constructor is getting called for each 'type' you have declared in the enum. ie BIG + SMALL

So the constructor is called to create BIG and also called again to create SMALL.

That is the only solution I can think of.

Thanks
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Alan is right: An enum is like a special kind of class, and an instance of it is made for each enum constant. Since you have two constants, BIG and SMALL, two instances are made. Note that Java enums are very flexible. You can, for example, add member variables and methods to an enum. See this for some examples: Java Enums.
 
He repaced his skull with glass. So you can see his brain. Kinda like this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic