Stupid Java Tricks to Amaze Your Friends

I was having a bit of a ponder about Java class names for inner classes. Consider the following class:

public class Example {

  public static void main(String[] args) {
    Thread thread = new Thread(
      new Runnable() {
        public void run() {
          System.out.println("Hi!");
        }
      });
      thread.start();
  }
}

When this class compiles, I’ll end up with two .class files. One is called Example.class and the other is called Example$1.class (which is how Java typically names anonymous inner classes).

Next I decided to screw with Eclipse. In Java 6, the dollar sign has become a valid character in Java names. I can create a class called “Example$1” as follows:

public class Example$1 implements Runnable {

  public void run() {
    System.out.println("Die!");
  }
}

Eclipse warns me when I use the “new class” Wizard that the dollar sign is discouraged, but after the class is created, there’s nothing to warn me that I’ve introduced a naming conflict.

Now, if I run Example, on my console view I see “Die!”. Hmmm.

Now I really want to screw with Eclipse. I change the second class, as follows:

public class Example$1 {

  public void run() {
    System.out.println("Die!");
  }
}

Note that I’ve removed the “implements Runnable”. Eclipse doesn’t think there are any compile errors in my code. But when I try to run the Example, I get an exception.

Exception in thread "Thread-0" java.lang.IncompatibleClassChangeError: Class Example$1 does not implement the requested interface java.lang.Runnable
	at java.lang.Thread.run(Thread.java:619)

Strange.

It's only fair to share...
Share on FacebookGoogle+Tweet about this on TwitterShare on LinkedIn

Leave a Reply