Why is String.length() a method?

后端 未结 8 806
难免孤独
难免孤独 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: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.

提交回复
热议问题