Java: When to create a final class

A final class is simply a class that can’t be extended.


This…final class Animal {



    …
}

class Dog …prevents this.extends Animal {



    …
}

It does not mean that all fields in the class are automatically final or that all references to this class would act as if they were declared as final.

When is this useful?

You should make a class final when the alternative—allowing subclassing—opens up for too many complications and becomes error prone.

Allowing subclassing may not seem like a big deal at first, but you should know that it’s notoriously difficult to get inheritance correct, and that it’s better to disallow it altogether than to get it wrong.

Here’s a non-exhaustive list of things to keep in mind when allowing classes to be extended:

Put differently: Class inheritance is a flexible language feature, and a powerful footgun.

Concluding with a quote from Effective Java:

Item 19: Design and document for inheritance or else prohibit it

[…] designing a class for inheritance requires great effort and places substantial limitations on the class.

[…] The best solution to this problem is to prohibit subclassing in classes that are not designed and documented to be safely subclassed. Joshua Bloch

Comments

Be the first to comment!