Search code examples
javaarraysclonesubclasssuperclass

How to copy elements of an array in superclass into an array in subclass in java?


Eg:

class A
{
    int array[] = {1,2,3,4,5}
}
class B extends A
{
    int new_array[];
}

Now here, I want to that new_array in class B should be containing the same elements as array in class A.

NOTE : I want to copy, but want to take care of that case where when we do any change in the copied array then the change should "not" be reflected in the original array.


Solution

  • After studying and surfing the web, I finally managed learned how to copy an array without using loops. The solution is as follows :

    class A
    {
        int array[] = {1, 2, 3, 4, 5};
    }
    class B extends A
    {
        int copyArray[] = array.clone();
    }
    

    I found this clone() method really helpful!