Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

clone

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
like image 461
Zecas Avatar asked Sep 27 '26 09:09

Zecas


1 Answers

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[].
like image 121
NPE Avatar answered Oct 01 '26 23:10

NPE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!