Sometimes classes or methods are just not designed to be subclassed, or it makes no sense to do so. By making those classes final, the developer of an API can indicate to the users of the API that those classes aren't meant to be subclassed.
There are lots of examples in the standard API: for example String, StringBuffer, System are all final classes.
Originally posted by prasath thirumoorthy: Hi Friends,
I know that final keyword is used for
1.If it is used before variable act as constant. 2.If it is used before method Avoid overriding to its subclasses. 3.If it is used in the class declaration Avoid Inheritance.
But my question is why there is a need to avoid inheritance, avoid method overriding ? give me an real time example in which case/situtation it will be useful.
Thanks & Regards, Prasath T
Final is not applied to variables to act as a constant; they are applied to 'variables' (to misuse terminology as the JLS has) to produce 'write once' fields, 'write once or not at all' locals, or constants. They are all very different things.
It is also not used to prevent inheritance, rather, to prevent concrete inheritance, which is different from legitimate inheritance. The argument regarding the illegitimacy of concrete inheritance is very controversial, mainly because of reasons that I am not permitted to say on this forum I assume due to the lack of orthodoxy and contradiction of critical mass belief, so instead I refer you to the search button above and google.
There are some definite risks to extending concrete classes, especially if you don't own the superclass. If you extended ArrayList Sun could change ArrayList in the future in ways that maintain their own interface contracts but break your code. If you owned both classes and one broke the other you'd fix them. It's all just time and money. Plenty of people live with these risks and don't burst into flames, but it is surely safer to never extend a concrete class. If you buy into that rule you might as well enforce the rule by making your concrete classes final.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi