为什么在Java中将String类声明为final? [英] Why is the String class declared final in Java?

查看:221
本文介绍了为什么在Java中将String类声明为final?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我得知在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.

不可变对象的一个优点是

您可以通过将重复副本指向单个实例来共享它们.

You can share duplicates by pointing them to a single instance.

(来自此处).

如果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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆