Re: enum question
www wrote:
I have three enums:
enum MyEnum
{
A, B, C, D
}
enum HisEnum
{
A, B, C, D, M, N
}
enum HerEnum
{
A, B, C, D, P
}
A, B, C, and D shows up three times in three enums. I am wondering if
the code can be improved to avoid such repeated coding. Ideally, I would
think MyEnum can be the "parent class" of HisEnum and HerEnum. But enum
cannot sublclass.
You could get something that looks like what you're looking for with
enum Omnus {
A, B, M, N, P;
XYZ whatever() {
...
}
}
class HisEnum {
static HisEnum A=new HisEnum(Omnus.A);
static HisEnum B=new HisEnum(Omnus.B);
static HisEnum M=new HisEnum(Omnus.M);
static HisEnum N=new HisEnum(Omnus.N);
private final Omnus mine;
HisEnum(Omnus which) {
mine=which;
}
XYZ whatever() {
return mine.whatever();
}
}
class HerEnum {
static HisEnum A=new HisEnum(Omnus.A);
static HisEnum B=new HisEnum(Omnus.B);
static HisEnum P=new HisEnum(Omnus.P);
private final Omnus mine;
HerEnum(Omnus which) {
mine=which;
}
XYZ whatever() {
return mine.whatever();
}
}
This allows you to code HisEnum.N but not HisEnum.P. It allows you to
declare a parameter, variable or return type to be HerEnum that can only
be A, B or P, but not M or N, which I assume is what you want. And
HisEnum.B.whatever() has the same value as HerEnum.B.whatever() and
Omnus.B.whatever().
--Mike Amling