For some reason the following code compiles fine in Java 5 but not Java 6.
Java 6 gives the following errors:
This code has compiled fine with Java 5 and earlier versions. Also Eclipse's built-in Java compiler produces no errors on the above code.
Any suggestions on how to maintain the functionality with a solution which works for Java 6?
Also, can anyone point to any Oracle Java 6 documentation that relates to a change which would introduce this compile error?
It has nothing to do with the Java version. It is a very simple error I have encountered myself. If you have something like this :
The testFrame has not been initialized, so the JDK says "I don't know what the variable is yet, because it hasn't been created." This is the same as your problem. Personally, I have not worked with enums (made my own "enums" with Strings), but I think you need to do something like this :
I feel these should be enough. If not, just google "type-safe enums Java".
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” (Mosher's Law of Software Engineering)
“If debugging is the process of removing bugs, then programming must be the process of putting them in.” (Edsger Dijkstra)
This is simply a case of the compiler being too stupid to understand what you want to do. The "illegal forward reference" is simply that when the compiler is looking at the code, the "forward reference" has not yet been seen, so its not defined. You can fix it by reordering your code.
Most of the time, the Java compiler is smart enough to internally handle it. But in this case, it fails. Its compiler version dependent, it may change with Java 7 or Java 8 or ....
Pat Farrell wrote:You can fix it by reordering your code.
Except with enums, because the enum constants need to be the first thing in the code.
A workaround is usually to use a helper class:
The reason it didn't work before is the way enums are handled when the class is loaded: first the enum constants are created, and any static fields are only instantiated after that. The enum constants cannot access anything that has not been initialized yet.
With this workaround, the enum constants ask for the Orientation fields. This causes the Orientation class to be loaded. This class is independent of the enum class, so its static fields are initialized without a problem. These can then be used in the enum constants.