We all know that String objects are immutable or we can say that String class can not be extended. Now since the String class is declared final.. it prevents anyone to extend that class. My main concern is to know when to declare Classes as final and why String class is declared final.
Acc. to many declaring classes as final increases performance but I read somewhere that
Most Java texts properly describe the usage and consequences of using the final keyword, but offer little in the way of guidance as to when, and how often, to use final. In my experience, final is vastly overused for classes and methods (generally because developers mistakenly believe it will enhance performance), and underused where it will do the most good -- in declaring class instance variables.
The main idea of making a class final is to restrict the user of your class from changing it. So if you feel, your class has a particular behavior which should not be changed, then you declare it to be final.
String class is final because if multiple references refer to the same object, then it is easier to change its value and hence the idea of maintaining the unique string literals in string contant pool will become useless.
I dont think that performance is an issue. Since the only problem while restricting a class to be final is the extensibility. The user cannot add to the behavior of your class.
The Real programming and constraints are always directly related to their usage in real time applications. The Desing patterns and OO practices are proven methods for the good design to build a better application.
For the answer why "final", you can search in Design patterns and OO principles, ... Some times we require , not to extend the functionality. and some times, close for modification and open for extension.
Class StringBuffer is a final class that is not immutable. You cannot extend it so you cannot override any of its methods. If the instances of StringBuffer were immutable like class String then StringBuffer would be useless. So making a class final protects the class from behavoural changes not state changes.
Whether or not to make a class or a method final is discussed in the article quoted above. [ September 19, 2006: Message edited by: Barry Gaunt ]