开发者

If a String is immutable, then why do you have to call a method to get the length instead of just accessing a variable, like array.length?

It seems to me that calling st开发者_运维知识库ring.length() each time takes significantly longer than just accessing a variable.


String implements interface CharSequence, which in turn defines length method. You couldn't do the same with variables since variables can't be abstract or overridden.
As other people say, Java is using interfaces heavily.


Because having access to the variable would allow you to modify it, and to break the String.

And the JIT compiler is smart enought to inline the getter for you, so you effectively are just accessing only the variable anyway.

Oh, and array.length is not a "real" object variable, but more like a language feature, allowing you to access the length of the array. Because of this it is not writable. Strings on the other hand are "normal" objects, and are not handled special be the compiler (Althought they are constructed somewhat on the fly when using String literals in the source code).


For encapsulation.

It is good practice to have a separation between public API and the implementation details. Using methods (instead of accessing internal variables directly) encapsulates the implementation, allowing it to be changed at any time without affecting any code which has already been written.


It is not because it is immutable. Even if it was mutable they could return a final length. Real answer is probably oversight.


It seems to me that's just java convention, that all members should be private and should only be accessible through Getters and Setters. Problem is if you make Length public you can modify it and make it invalid (not sure why you would do that but who knows).

C# changes this by allowing you to create properties with different accesibility for get and set which is why that is allowed (in C# at least).


It's because a String is an object. And objects usually have methods instead of attributes.

If the attribute was public, you could also modify it and that would probably break things.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜