为什么String.length()是一个方法? [英] Why is String.length() a method?

查看:130
本文介绍了为什么String.length()是一个方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果String对象是不可变的(因此显然不能改变它的长度),为什么 length()一个方法,而不是简单地 public final int length 比如数组中有?

If a String object is immutable (and thus obviously cannot change its length), why is length() a method, as opposed to simply being public final int length such as there is in an array?

它只是一个getter方法,还是进行某种计算? ?

Is it simply a getter method, or does it make some sort of calculation?

只是想看看背后的逻辑。

Just trying to see the logic behind this.

推荐答案

Java是一种标准,而不仅仅是一种实现。不同的供应商可以以不同的方式许可和实施Java,只要它们符合标准即可。通过对字段进行标准调用,可以非常严格地限制实现。

Java is a standard, not just an implementation. Different vendors can license and implement Java differently, as long as they adhere to the standard. By making the standard call for a field, that limits the implementation quite severely, for no good reason.

此外,方法在未来方面更加灵活。类。除了在一些非常早期的Java类中,几乎从未完成将最终常量暴露为可以与类的每个实例具有不同值的字段,而不是作为方法。

Also a method is much more flexible in terms of the future of a class. It is almost never done, except in some very early Java classes, to expose a final constant as a field that can have a different value with each instance of the class, rather than as a method.

length()方法早于CharSequence接口,可能是它的第一个版本。看看效果如何。多年以后,没有任何向后兼容性的损失,CharSequence接口被引入并且非常适合。对于一个字段来说这是不可能的。

The length() method well predates the CharSequence interface, probably from its first version. Look how well that worked out. Years later, without any loss of backwards compatibility, the CharSequence interface was introduced and fit in nicely. This would not have been possible with a field.

所以让我们真正颠倒这个问题(当你设计一个数十年来保持不变的类时,你应该做什么) :一个领域在这里获得了什么,为什么不简单地使它成为一种方法?

So let's really inverse the question (which is what you should do when you design a class intended to remain unchanged for decades): What does a field gain here, why not simply make it a method?

这篇关于为什么String.length()是一个方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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