Search This Blog

Tuesday, 5 October 2010

Java puzzle - the solution

Though no-one's actually commented on the Java puzzle, I know at least two who attempted it... and one who, after a hint, got it bang on.

The key is that anonymous inner class that actually gets compiled into a separate class file - Main$1.class. It's this class that contains the code which prints out hello, so the following compiled and dropped in place would cause the program to print goodbye, without modifying Main.class:

package bosscode;

public class Main$1 implements Runnable {
public void run() {

The java.lang.Runnable in the original code was deliberately there to prevent the creation of an additional Runnable class in the bosscode package, which would have worked had Runnable not been declared with its package!

This actually highlights an interesting problem - it's entirely legal as far as the compiler's concerned to create a Main class and a Main$1 class in the same package, creating naming conflicts. Whilst this may seem unlikely, if the inner class isn't anonymous the name will take the form of Outer$Inner - so the potential is there to cause issues. In fact, whilst experimenting around with this puzzle in Netbeans it didn't show me any warnings that I'd created such a conflict, the last class to be compiled was just the one that dictated the output.

Of course, we can solve this problem altogether by never using a dollar sign in class names explicitly, reserving it as a special symbol for the compiler to use. I do wonder why this isn't strictly enforced though - it'd eliminate this problem (and this puzzle!) altogether.

No comments:

Post a Comment