From when I learned that the class java.lang.String
is declared as final in Java, I was wondering why that is. I didn't find any answer back then, but this post: How to create a replica of String class in Java? reminded me of my query.
Sure, String provides all the functionality I ever needed, and I never thought of any operation that would require an extension of class String, but still you'll never know what someone might need!
So, does anyone know what the intent of the designers was when they decided to make it final?
It is very useful to have strings implemented as immutable objects. You should read about immutability to understand more about it.
One advantage of immutable objects is that
You can share duplicates by pointing them to a single instance.
(from here).
If String were not final, you could create a subclass and have two strings that look alike when "seen as Strings", but that are actually different.