Why can't have enum extending some class in Java?
Examples below shows, that:
E1
.E2
.For example:
public class Try_ExtendEnum {
public static enum E1 {
North,
East,
South,
West
}
public static enum E2 {
North(0),
Eash(90),
South(180),
West(270);
private double degrees;
E2(double degrees) {
this.degrees = degrees;
}
public double getDegrees() {
return degrees;
}
}
public static class DegreesMeasure {
private double degrees;
public DegreesMeasure(double degrees) {
this.degrees = degrees;
}
public double getDegrees() {
return degrees;
}
}
public static enum E3 extends DegreesMeasure {
North(0),
Eash(90),
South(180),
West(270);
E3(double degrees) {
super(degrees);
}
}
public static void main(String[] args) {
DegreesMeasure dm = new DegreesMeasure(123);
E3 e = dm; // should not be possible, since E3 is a subclass and not obliged to hold superclass
DegreesMeasure dm2 = E3.Nort; // just holding "tagged" version of instance; see no any problem
}
}
An enum
cannot extends
another class because an enum
already extends Enum<T>
. That class provides all the enum
functionality.
An enum
can, however, implements
an interface
:
public interface DegreesMeasure {
double getDegrees();
}
public enum E3 implements DegreesMeasure {
NORTH(0),
EAST(90),
SOUTH(180),
WEST(270);
private final double degrees;
E3(double degrees) {
this.degress = degrees;
}
@Override
public double getDegrees() {
return degrees;
}
}
And this would seem to make a lot more sense in your case anyway.
Also, traditionally, as an enum
value is in essence a public static final
value it is named in the same way - in block caps with underscores.
EDIT
From comments - how to override methods in individual enum
values. This is often used in a Factory Pattern. Assume we have a Widget
and a WidgetFactory
. We have two different widget types, small and large. These are represented by the classes SmallWidget
and LargeWidget
.
interface Widget {}
interface WidgetFactory {
Widget get();
}
class LargeWidget implements Widget {}
class SmallWidget implements Widget {}
Now we can implement the WidgetFactory
as an enum
thus:
enum WidgetFactoryImpl implements WidgetFactory {
SMALL {
@Override
public Widget get() {
return new SmallWidget();
}
},
LARGE {
@Override
public Widget get() {
return new LargeWidget();
}
};
}
In general having polymorphic behaviour on enum
can be extremely powerful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With