Why standard java classes's clone() return Object instead of actual type
Backwards compatibility.
Prior to Java 5, the return type could not be narrowed when overriding, so ArrayList.clone()
was declared to return Object
. Now that the language permits that, they can't use it, because narrowing the return type of ArrayList.clone()
would break existing subclasses of ArrayList that override ArrayList.clone()
with return type Object
.
One reason is backwards compatibility. The signature of the Object.clone()
method was specified way back in Java 1.0, when there wasn't support for covariant return types. If they changed this fundamental method as you suggested, it could break thousands of legacy programs where the clone()
method might not return an object with the same type as this
.
See also:
- Would using covariant return type in clone really break compatibility?
- Why doesn't Java 5+ API take advantage of covariant return types?