Many classes in the Core Java API are final (Wrapper classes, String, Math). Why is it so ?
-
Ask whoever invented those packages. My guess would be either "just because", or "so the JDK would be guaranteed to work with Strings and Wrapper classes" (avoiding issues with subclasses that change behavior). – Dave Newton May 01 '12 at 18:31
-
Because they are not meant to be extended? – assylias May 01 '12 at 18:33
-
Duplicate: http://stackoverflow.com/questions/2068804/why-is-string-final-in-java – Mat May 01 '12 at 18:37
2 Answers
They are final for security reasons. There may be other reasons, but security is the most important.
Imagine an ability to inherit java.lang.String
, and supply your own, mutable implementation to a security-sensitive API. The API would have no choice but take your string (remember the substitution principle) then but you would be able to change the string from under them (on a concurrent thread or after the API has returned), even after they have checked it to be valid.
Same goes for wrappers of primitives: you do not want to see them mutable under any circumstance, because it would violate important assumptions about their behavior encoded in the APIs using these classes.
Making String
final addresses this issue by not letting others supply their own, potentially hostile, implementations of classes as fundamental as String
.

- 714,442
- 84
- 1,110
- 1,523
You might want to prevent other programmers from creating subclasses or from overriding certain methods. For these situations, you use the final keyword.
The String class is meant to be immutable - string objects can't be modified by any of their methods. Since java does not enforce this, the class designers did. Nobody can create subclasses of String.
Hope this answers your question.

- 41
- 5
-
It shouldn't; it explains what `final` *does*, but is not an explanation for *why* those particular classes are `final`. – Dave Newton May 01 '12 at 18:35
-
1
-
Is there any concept between final class ,dynamic class loading and security .Plz explain . – Sumeet Kumar May 03 '12 at 03:53