Good reasons to prohibit inheritance in Java?
You might want to make a method final so that overriding classes can't change behavior that is counted on in other methods. Methods called in constructors are often declared final so you don't get any unpleasant surprises when creating objects.
Your best reference here is Item 19 of Joshua Bloch's excellent book "Effective Java", called "Design and document for inheritance or else prohibit it". (It's item 17 in the second edition and item 15 in the first edition.) You should really read it, but I'll summarize.
The interaction of inherited classes with their parents can be surprising and unpredictable if the ancestor wasn't designed to be inherited from.
Classes should therefore come in two kinds:
Classes designed to be **extended**, and with enough documentation to describe how it should be done
Classes marked **final**
If you are writing purely internal code, this may be a bit of overkill. However, the extra effort involved in adding five characters to a class file is very small. If you are writing only for internal consumption, then a future coder can always remove the 'final' - you can think of it as a warning saying "this class was not designed with inheritance in mind".
One reason to make a class final would be if you wanted to force composition over inheritance. This is generally desirable in avoiding tight coupling between classes.
There are 3 use cases where you can go for final methods.
- To avoid derived class from overriding a particular base class functionality.
- This is for security purpose, where base class is giving some important core functionality of the framework where derived class is not supposed to change it.
- Final methods are faster than instance methods, as there is no use of virtual table concept for final and private methods. So where ever there is a possibility, try to use final methods.
Purpose for making a class final:
So that no body can extend those classes and change their behavior.
Eg: Wrapper class Integer is a final class. If that class is not final, then any one can extend Integer into his own class and change the basic behavior of integer class. To avoid this, java made all wrapper classes as final classes.