I've been attempting to implement an interface in my enums in order to have rules for a simulation I'm making.
I am trying to access enum-methods such as values()
and ordinal()
(on objects).
However, even with upper-bounding my classes with my interface name, I still cannot access these methods without overriding them in my interface, which won't work.
public interface State{
public static void setTileSize(int size){
return;
}
public void draw(PApplet app, int x, int y);
public Object updateState(int[] allNeighbours);
public int getColour();
}
enum WireWorld implements State{ // WireWorld
WIRE(new Color(100, 100, 100)) {
public WireWorld updateState(int[] allNeighbours){
if (allNeighbours[1] >= 1){
return TIP;
}
return WIRE;
}
}, ...
public class Tile<T extends State> {
public Tile() {
int enumCount = T.values().length;
}
}
I'm trying to call the constructor on Tile and it doesn't work.
You need to provide an indication that
T
extendsEnum
as it was mentioned by @Slaw in the comments.We can declare multiple type bound by chaining them using ampersand sign
&
and sinceEnum
is a class it needs to be mentioned before interfaceState
(see) :Assuming that
Tile
is meant to hold a reference to an enum member of typeT
and invoke methods likeordinal()
andname()
on it. Now compiler will allow doing that, since it knows thatT extends Enum<T>
.And seems like your intention was to define an instance variable
enumCount
in theTile
class that will hold a number of enum members. In order to initialize it, you need to provide an instance ofClass<T>
as a parameter to the constructor. And one of the way to get access to all enum constantsClass<T>
is throughEnumSet.allOf()
.