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

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

问题描述

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

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.

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

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