Why is String.length() a method?

后端 未结 8 759
难免孤独
难免孤独 2020-11-30 10:34

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 lengt

相关标签:
8条回答
  • 2020-11-30 11:00

    String is using encapsulation to hide its internal details from you. An immutable object is still free to have mutable internal values as long as its externally visible state doesn't change. Length could be lazily computed. I encourage you to take a look as String's source code.

    0 讨论(0)
  • 2020-11-30 11:05

    This is a fundamental tenet of encapsulation.

    Part of encapsulation is that the class should hide its implementation from its interface (in the "design by contract" sense of an interface, not in the Java keyword sense).

    What you want is the String's length -- you shouldn't care if this is cached, calculated, delegates to some other field, etc. If the JDK people want to change the implementation down the road, they should be able to do so without you having to recompile.

    0 讨论(0)
提交回复
热议问题