Why is String.length() a method?

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

提交回复
热议问题