Archive for June, 2013

Be Careful When Hacking Into A Java Class

June 3, 2013 Leave a comment

I recently stumbled over a blog post that explains the usage of Java Anonymous Classes. Not being very happy with the example that was given to show the discussed language feature in action, I left a rather critical comment which I want to explain in more detail:

Tweaking existing classes on the fly is a legitimate use of Java Anonymous Classes. Still, as doing so involves inheritance, the usual rules apply:

  • The anonymous class should be in a is-a relationship to its parent. This is not true for the LinkedList in the example given here, as the tweaked add method clearly violates the specification of Collection.add(…).
  • Inheriting from classes that are not designed for inheritance is dangerous, as unlike composition and method invocation, inheritance violates encapsulation. By carelessly inheriting from a random class, you might create strong ties to the implementation of said class without even knowing. Again referring to the queue from here, imagine what would happen if somebody called queue.addAll(…). As it turns out, this very much depends on whether LinkedList.addAll(…) is implemented using LinkedList.add(…) or not, which of course is an implementation detail that is not mentioned in the Javadocs. It might vary between different class library vendors and versions. I strongly recommend reading Items 16 and 17 from Effective Java in this context.

Having said that, I still have explain why I would rather use

private static final ThreadLocal<Integer> someThreadLocalInt =
    new ThreadLocal<Integer>() {
      protected Integer initialValue() {
        return 42;

to illustrate a typical use of Java Anonymous Classes for tweaking an existing implementation. The reason for this is that ThreadLocal is designed for inheritance, while LinkedList is not. I know this, because the Javadocs for ThreadLocal contain information for clients who want to extend this class while the Javadocs for LinkedList don’t.

Categories: Programming Tags: ,