Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are Wrapper Classes, String,... final ?

Tags:

java

oop

Many classes in the Core Java API are final (Wrapper classes, String, Math). Why is it so ?

like image 900
Sumeet Kumar Avatar asked Jun 22 '26 08:06

Sumeet Kumar


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.

like image 66
Sergey Kalinichenko Avatar answered Jun 24 '26 20:06

Sergey Kalinichenko


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.

like image 22
Sho'vah Avatar answered Jun 24 '26 20:06

Sho'vah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!