• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Strange behaviour of enum

 
Andry Dub
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • 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");
}
}
 
Alan Heebson
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • 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
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15205
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • 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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic