wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Regarding Enum access specifier Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Regarding Enum access specifier" Watch "Regarding Enum access specifier" New topic
Author

Regarding Enum access specifier

sharma ishu
Ranch Hand

Joined: Sep 10, 2012
Posts: 70
Please explain what does this line means.

"The constructor for an enum type must be package-private or private access."
Guillaume Jourdan
Ranch Hand

Joined: Jul 24, 2012
Posts: 47

This sentence means that you can't implement an enum outside the enum class definition. By default, an enum have a private default constructor, but you can define your own constructor.

Example :

John Jai
Bartender

Joined: May 31, 2011
Posts: 1776
Please UseAMeaningfulSubjectLine henceforth. I have modified it for you this time.
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4344
    
    8

And to add to what Guillaume said - try adding a constructor to the enum that has a public or protected modifier. You should get a compiler error.

To be honest, I'm not sure why they allow a package-accessible constructors as well as private, but it may be just so that you can get away with not giving a modifier.
sharma ishu
Ranch Hand

Joined: Sep 10, 2012
Posts: 70
Matthew Brown wrote:And to add to what Guillaume said - try adding a constructor to the enum that has a public or protected modifier. You should get a compiler error.

To be honest, I'm not sure why they allow a package-accessible constructors as well as private, but it may be just so that you can get away with not giving a modifier.


But we cannot say like: new EnumType();
So, what difference does it make that what access modifier is used for the constructor.
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4344
    
    8

sharma ishu wrote:But we cannot say like: new EnumType();
So, what difference does it make that what access modifier is used for the constructor.

Look at it the other way: since you can't go new EnumType(), what possible reason could there be to have a public or protected constructor? There's a general tendency in the design of Java to disallow things that don't make sense.
RajaShekhar Gundeti
Greenhorn

Joined: Nov 23, 2012
Posts: 2
It seems enums are used to declare a fixed set of meaningful constants. so, it doesn't allow creations of enums dynamically at runtime by restricting using access specifier. enums are static and compile.
 
 
subject: Regarding Enum access specifier
 
Similar Threads
How are enum constructors initialised
access control modifier for enum
Enum constructor
enum cannot be private or protected
How to define constants for several classes?