Sunday 20 September 2009

Item 22: Favor static member classes over nonstatic

This item covers a little more than its title suggests. As well as static and non-static member classes, it also covers anonymous classes (a favourite of mine) and local classes.

Syntactically the only difference between static and nonstatic member (nested) classes is that static members classes have the modifier static in their declarations. In short, an instance of a nonstatic member class can only exist in conjunction with an instance of its outer class. An instance of a static class can exist on its own without an instance of the outer class. If you declare a member class that does not require access to an enclosing instance, always make it a static class by putting the static modifier in its declaration.

The item doesn't make a particularly strong argument for favouring static classes over nonstatic classes. In fact the only arguments seem to be that you can use a nonstatic nested class instance without an outer class instance and that nonstatic nested classes take up more space and take longer to create than static classes due to the reference to their outer class instance.

Paul Grenyer

No comments: