This week's book giveaway is in the Big Data forum.
We're giving away four copies of Elasticsearch in Action and have Radu Gheorghe & Matthew Lee Hinman on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Strange behaviour of enum Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Elasticsearch in Action this week in the Big Data forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Strange behaviour of enum" Watch "Strange behaviour of enum" New topic

Strange behaviour of enum

Andry Dub
Ranch Hand

Joined: Nov 06, 2007
Posts: 43
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{

Size() {

Java is my love
Alan Heebson

Joined: Nov 05, 2007
Posts: 5
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.

Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14599

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.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
I agree. Here's the link:
subject: Strange behaviour of enum