Java: When to create a final class

A final class is simply a class that can’t be extended. This will for example not compile:


final class Animal {
    …
}

class Dog extends Animal {
    …
}

It does not mean

  • that all references to this class would act as if they were declared as final, or
  • that all fields in the class are automatically final

So when is this useful?

Being able to extend a class is a flexible feature. In fact it’s so flexible that it can be tricky to forsee all possible ways a class can be extended. So, unless you take care to design your class to allow for extension and document how methods may be overridden etc, you might be better off marking the class as final as a defensive measure. This is especially true if the class is part of a library that you hand out to other developers.

Comments

Be the first to comment!