Java Definition order matters

Ever encountered a illegal forward reference in Java? Thought that those days were gone and that compilers finally managed to get the initialization order right. Well, turns out not in all cases.

The Java Language Specification tackles that topic in section It basically says the declaration has to textually appear before another if it's used in a member initialization expression.

The static initializer also has this restriction. Well perhaps thats a reason, why many Java programmers declare Variables at the beginning of their class. I still think thats not the best approach, as the public interface - which should give the best overview of the class - should appear first (textually) to ease comprehension.

No comments: