Re: Using an enum in a constructor
Sorry if this gets double posted. GG is on the fritz again!
On Sep 23, 11:21 am, Wojtek <nowh...@a.com> wrote:
Daniel Pitts wrote :
On Sep 20, 4:38 pm, Wojtek <nowh...@a.com> wrote:
Roedy Green wrote :
On Thu, 20 Sep 2007 20:33:13 GMT, Wojtek <nowh...@a.com> wrote, quoted
or indirectly quoted someone who said :
public class Foo
{
private static final int DEFAULT_LENGTH = 30;
private Type ivType;
private int ivLength;
public enum Type
{
OTHER,
FIXED,
VARIABLE;
}
You have this as a nested inner instance class. I have always made my
enums separate top level classes. Perhaps you are allowed to define
them as static inner classes. Perhaps there are magic exceptions made
for enums to the usual nesting rules. Is there a language lawyer
about?
We have had this discussion before, but I do not remember seeing your
example.
If I use the above, then I reference it with Foo.Type.FIXED.
What does your separate top level enum class look like, and how do you
reference it?
--
Wojtek :-)
/* MySeperateEnum.java */
public enum MySeperateEnum {
A,B,C;
}
/*SomeOtherClass.java*/
public class SomeOtherClass {
MySeperateEnum value = MySeperateEnum.A;
}
Ah, ok, I see now. This enum beast is kind of a funny sort of class....
Actually, it is in more ways than you might suspect.
enum MyEnum {
A {
public void doSomething() {
System.out.println("Something on A");
}
},
B{
public void doSomething() {
System.out.println("B does something");
}
},
C{
public void doSomething() {
System.out.println("C you later!");
}
};
public abstract void doSomething();
}
MyEnum is an abstract base class of MyEnum.A (and .B, etc..). You can
add methods, fields (good practice to make those final), and even
constructors to the enum and members. You can even add members to the
specifics (MyEnum.A) that aren't in the parent (MyEnum).
I've used this idiom to implement the flyweight pattern in conjunction
with the strategy/state pattern. Although, I usually find that
eventually I need even more flexibility (better polymorphic
structure), and end up refactoring away from the enum approach. Not
to say enums aren't a good interim step, or prototype step before that
approach.
So I can create a separate class for the enum (as per your example), or
nest it in the class where it is used (as per my example).
So if it is being used elsewhere in the system I need two import
statements vs one.
I don't count imports as statements personally. I think of them more
as directives. You can always give the fully qualified class name in
place of using the imports.
I kind of prefer the nesting approach, as the location (and reference)
indicates the enums logical ownership.
Indeed. If the enum has a logical owner, then it makes much sense to
have that owner, ahem, own it!
On the other hand, if it doesn't have a *single* logical owner (which
does happen on occasion), it should probably be its own separate
entity.
Good luck,
Daniel.