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

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

问题描述

从我得知在Java中将类 java.lang.String 声明为final时,我想知道为什么会这样?我当时没有找到任何答案,但这篇文章:如何在Java中创建String类的副本?让我想起了我的查询。

From when I learned that the class java.lang.String is declared as final in Java, I was wondering why is that? 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 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 was the intent of the designers 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.

这篇关于为什么String类在Java中声明为final?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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