Why is String.length() a method?

后端 未结 8 807
难免孤独
难免孤独 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 10:43

    Perhaps a .length() method was considered more consistent with the corresponding method for a StringBuffer, which would obviously need more than a final member variable.

    The String class was probably one of the very first classes defined for Java, ever. It's possible (and this is just speculation) that the implementation used a .length() method before final member variables even existed. It wouldn't take very long before the use of the method was well-embedded into the body of Java code existing at the time.

提交回复
热议问题