It's allowed in java to specify type of function return, for example following code
public class Test {
static class Dad {
Dad me() {
return this;
}
}
static class Son extends Dad {
Son me() {
return this;
}
}
}
is valid.
Let's see ArrayList
class. It has overridden clone()
function (At least I see it in Oracle jdk 1.7 source)
public Object clone() {
try {
@SuppressWarnings("unchecked")
ArrayList<E> v = (ArrayList<E>) super.clone();
v.elementData = Arrays.copyOf(elementData, size);
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError();
}
}
What's the point not to return ArrayList<E>
but just Object
?
clone() method returns a Shallow Copy. In shallow copy, if the field value is a primitive type, it copies its value; otherwise, if the field value is a reference to an object, it copies the reference, hence referring to the same object. Now, if one of these objects is modified, the change is visible in the other.
clone() method is protected i.e. accessed by subclasses only. Since object is the parent class of all sub classes, so Clone() method can be used by all classes infact if we don't have above check of 'instance of Cloneable'.
The clone() method isn't defined by the Cloneable interface. The clone method in the Object class is protected to prevent a client class from calling it - Only subclasses can call or override clone, and doing so is a bad idea.
The clone() method is used to create a copy of an object of a class which implements Cloneable interface. By default, it does field-by-field copy as the Object class doesn't have any idea about the members of the particular class whose objects call this method.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With