File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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 Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Strange behaviour of enum" Watch "Strange behaviour of enum" New topic
Author

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{
BIG,SMALL;

Size() {
System.out.println("constructor");
}
}


Java is my love
Alan Heebson
Greenhorn

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.

Thanks
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074
    
  16

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 7 API documentation
Scala Notes - My blog about Scala
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Strange behaviour of enum
 
Similar Threads
Annotations for Enum Constants
confusion regardind enum and constructors
Enum programs are not compiling in java5.0 compiler?
Enum overloaded constructer
Enum Constructor - Exception and Accessibility