I'm programming a game in java which is made up of a grid of tiles. I wan't to be able to inuitively define the edges of the tiles and how they relate to each other, e.g. to get the opposite edge of a tile, I want to be able to just type TOP.opposite()
. However, when using enums to define these edges I end up having to forward reference at least two of them in the contstructor:
public enum Edge { TOP(Edge.BOTTOM), //illegal forward reference BOTTOM(Edge.TOP), LEFT(Edge.RIGHT), //illegal forward reference RIGHT(Edge.LEFT); private Edge opposite; private Edge(Edge opp){ this.opposite = opp; } public Edge opposite(){ return this.opposite; } }
Is there any way of getting round this problem using enums which is just as simple?
"Illegal forward reference" means that you are trying to use a variable before it is defined. The behavior you observe is a symptom of a javac bug(see this bug report). The problem appears to be fixed in newer versions of the compiler, e.g. OpenJDK 7.
You pass references, not objects. References are passed by value. You can change the state of a mutable object that the reference points to in a function that it is passed into, but you cannot change the reference itself.
You can't do it, since the language does not allow you. And for a good logical reason: subclassing an enum would only make sense if you could remove some enum values from the subclass, not add new ones. Otherwise you would break the Liskov Substitution Principle.
Because there is only one instance of each enum constant, it is permissible to use the == operator in place of the equals method when comparing two object references if it is known that at least one of them refers to an enum constant.
You can do this which is not as intuitive.
public enum Edge { TOP, BOTTOM, LEFT, RIGHT; private Edge opposite; static { TOP.opposite = BOTTOM; BOTTOM.opposite = TOP; LEFT.opposite = RIGHT; RIGHT.opposite = LEFT; } public Edge opposite(){ return this.opposite; } }
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