Nelz's Blog

Mah blogginess

Applying the Java Keyword 'Final' to Classes

I was ponderin’ the usages of the final keyword as applied to classes in Java.

I have heard before that all classes should be defined as final by default. The theory goes that unless you are specifically designing (and testing) your classes as potentially extensible, the final class modifier is a nice ‘pertinent negative’.

In practice, this theory falls apart.

If you are exposing your concrete classes to other clients, a final class can neuter the consumer’s ability to mock your class for testing purposes. (I ran into this at one point when using Lucene at work, and tried to mock out a class.)

Another problem that arises, even if you have hidden all your concrete classes behind a nice API, is that final classes are not accessible by AOP. (At least, not in the framework that I looked into.)