Jean John wrote:Hi,
I found the below code in SCJP book for Java 6 Exam and I have a doubt regarding the comment that enclosing class name is required. I tried without using the enclosing class name and still it works. The jdk i have right now is 1.6
The book mentions that the syntax for accessing an enum's members depends on where the enum was declared. But even if the enum is declared inside or outside the class, I can access the enum using the same syntax. ie. without enclosing class name. Can someone please bring out some clarity regarding this statement.Thanks.
why are you using class name ? that is not right way.It is not matter that enum is declared and defined outside or inside..this'll be correct always
Declaring an enum outside a class:
The preceding code can be part of a single file. (Remember, the file must be named
CoffeeTest1.java because that's the name of the public class in the file.) The
key point to remember is that an enum that isn't enclosed in a class can be declared
with only the public or default modifier, just like a non-inner class. Here's an
example of declaring an enum inside a class:
The key points to take away from these examples are that enums can be declared
as their own class, or enclosed in another class, and that the syntax for accessing
an enum's members depends on where the enum was declared.
Prithvi Sehgal wrote:Dear Jean,
But when an enum is part of a class, you have to use the enclosing class name, else it won't
compile. Just think logically, how will other class know where the enum is declared so you need to specify the class
name, when an enum is present inside the class.
Prithvi Sehgal wrote:Nitesh,
Just look at the code properly. When the enum is inside another class, you need to give the name of the enclosing class.
The case you are talking about is, when enum is outside class or inside same class. We are discussing the case when enum
is part of another class. As the context changes, the using class will never know where that enum is and will complain a compile