Why doesn't Object.clone() call need an explicit cast? Isn't this an exception to the "downcast always need and explicit cast" rule? I compiled and successfully run the following code using both javac command-line and Eclipse Helios with JDK1.6.0_29.
public class Main {
public static void main(String[] args) {
byte[] original = { 1, 2, 3, 4 };
byte[] copy = original.clone();
for (byte b : copy) {
System.out.print(b + " ");
}
int[] originalInt = { 11, 22, 33, 44 };
int[] copyInt = originalInt.clone();
for (int i : copyInt) {
System.out.print(i + " ");
}
String[] originalStr = { "1", "2", "3", "4" };
String[] copyStr = originalStr.clone();
for (String s : copyStr) {
System.out.print(s + " ");
}
Main[] originalMain = { new Main() };
Main[] copyMain = originalMain.clone();
for (Main m : copyMain) {
System.out.print(m + " ");
}
} // end method main
} // end class Main
You are not calling Object.clone(). You are calling T[].clone(), which is overridden to return T[].
JLS 10.7 Array Members:
The members of an array type are all of the following:
- The public method
clone, which overrides the method of the same name in classObjectand throws no checked exceptions. The return type of theclonemethod of an array typeT[]isT[].
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