When writing a new class, start with
static final class Foo {}
I've read many times that declaring a class as final is a farily dangerous thing to do with code. Once you've made a class final people are stuck with what you decided at a particular moment was the right way to do things. Can you truly know that the class will never have to change in the future? That's a tough call to make.
Well, think of it from the other side - if you *don't* make it final, you're essentially inviting anyone to subclass it for any reason, and promising that whatever they do, any changes you make to the class will work with their subclass. Do you know how they're going to subclass it? Which methods are they going to override, exactly, in which combination? Are any of the overridable methods called from the constructor? If you use a synchronization monitor, are they going to use the same one? If you decide to deprecate one method in favor of a new one you add, how will the class behave if subclasses are still overriding the old one? Is the class comparable, or does it use equals(), is it clonable or serializable or externalizable? There's a surprisingly large number of ways you can get into a royal mess as APIs evolve, at least in my experience, and nonfinal classes are much harder to reason about.
An example: javax.swing.tree.TreePath is nonfinal. The authors of the class were polite enough to even provide a no-arg subclass constructor and things like this. So this sounds cool - you can make a special TreePath that is specialized to unusual JTree storages! Well, unfortunately, no - it turns out that it is not possible to subclass it usefully, since you can't get rid of some of the fields in the superclass, and you can't make equals() work correctly with non-subclassed TreePath's, and in fact the Javadoc for the class lies about which methods you really need to override together. But you would never notice this kind of thing looking at the class casually.
On the other hand, if you make a class final, and it turns out later that there is a good reason to subclass it, and it seems safe and effective, you can remove the final modifier then, without breaking anything.
But here I feel like a complete novice, practically every day I'm learning something new about a particular idiosyncratic aspect of Java - which is great!
Oh yes... I still feel pretty clueless about a lot of Ant internals - e.g. macrodefs! - so I wind up posting about something I can recognize. :-)
-J.
-- Jesse Glick <mailto:[EMAIL PROTECTED]> x22801 NetBeans, Open APIs <http://www.netbeans.org/>
--------------------------------------------------------------------- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]