Zecas
Zecas

Reputation: 647

Shouldn't Object.clone() need explicit cast?

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

Answers (1)

NPE
NPE

Reputation: 500277

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 class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].

Upvotes: 5

Related Questions