这是一道出于好奇的问题。
今天我研究了StringBuilder
和StringBuffer
的实现。这里是它们的append()
方法:
public StringBuilder append(String str) {
super.append(str);
return this;
}
AbstractStringBuilder.append(str)
方法也返回 this
。在 StringBuilder.append(..)
中,舍弃返回值并再次返回 this
,有什么好处呢?与其将 super
调用的返回值转换为当前具体实现,不如直接返回 this
。