Reputation: 647
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
Upvotes: 3
Views: 106
Reputation: 500277
You are not calling Object.clone()
. You are calling T[].clone()
, which is overridden to return T[]
.
The members of an array type are all of the following:
- The public method
clone
, which overrides the method of the same name in classObject
and throws no checked exceptions. The return type of theclone
method of an array typeT[]
isT[]
.
Upvotes: 5