问题描述
当我得知在Java中将类java.lang.String
声明为final时,我想知道为什么会这样.那时我没有找到任何答案,但是这篇文章:使我想起了我的查询.
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.
当然,String提供了我所需要的所有功能,而且我从未想到过需要扩展String类的任何操作,但是您仍然永远不会知道有人可能需要什么!
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.
不可变对象的一个优点是
(来自此处).
如果String不是最终的,则可以创建一个子类,并具有两个字符串,当视为字符串"时看起来相似,但实际上是不同的.
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.
这篇关于为什么在Java中将String类声明为final?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!