Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Illegal Forward Reference and Enums

Tags:

java

enums

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?

like image 503
MattLBeck Avatar asked Apr 15 '11 14:04

MattLBeck


People also ask

What is illegal forward reference in Java?

"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.

Are enums passed by reference?

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.

Can enums be subclassed?

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.

Can you use == for enums?

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.


1 Answers

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;     } } 
like image 171
Peter Lawrey Avatar answered Sep 28 '22 06:09

Peter Lawrey