Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Enum Constructor - Exception and Accessibility

 
Chinmay Naik
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have following questions about Enums:

1) Can an enum constructor throw any checked exceptions?
I wrote the following code but I am getting compile time error saying unhandled exception of type Exception.

Can somebody please explain why? Is there any way, wherein we can write enum constructor that throws some checked exception?
=========================================================================================
2) Also, can somebody tell me why compiler does not allow me to declare enum constructor of any enum as public or protected. It says, only private is permitted. However, I could declare enum constructor with no modifier (i.e. with default scope). So why only default scope and private scope is allowed for enum constructors?
 
Alfred Swensen
Greenhorn
Posts: 10
Netbeans IDE PHP VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Chinmay Naik wrote:
1) Can an enum constructor throw any checked exceptions?


AFAIK, no. To understand enums I try to think of them as pure syntactic suger, behind the scenes the java compiler could (at least theoretically) be transform them into a plain old java class before compiling them:



If you try to compile that, you see that you get exactly the same error message, but now you understand why the Exception is illegal:





2) Also, can somebody tell me why compiler does not allow me to declare enum constructor of any enum as public or protected. It says, only private is permitted.
However, I could declare enum constructor with no modifier (i.e. with default scope). So why only default scope and private scope is allowed for enum constructors?


public and protected are forbidden because then you would imply that you are planning to call the constructor from outside the class - as Enums may only consist
of compile time constants, this must be prohibited.

Regarding the "default" access level, I tend to use my above explanation that an enum is just a convenience representation and that the compiler will add an "private" implicitly before compiling it.

 
karthick chinnathambi
Ranch Hand
Posts: 196
Android Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this is to prevent you from calling enum-constructor explicitly......
you can't call an enum constructor explicitly
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic