Search code examples
javaclone

How to implement a deep copy of an object that contains an array of objects in Java?


I need to make a class called Garage implement Cloneable and override the Object.clone() method to make a deep copy of an object of type Garage which contains an array of objects of type Vehicle.

I have read on several SO answers that Cloneable is broken and it is wise not to use it, but my lab assignment demands that I implement Cloneable and code a proper clone() method. I have been looking for long but still haven't been able to do this. Any help would be much appreciated.

This is my code for the Garage class:

public class Garage extends Vehicle implements Cloneable {
    // array to store up to 15 Vehicle objects
    Vehicle array[] = new Vehicle[15];

    // overriding the clone method to perform a deeper copy
    @Override
    protected Object clone() throws CloneNotSupportedException {
        //TODO
    }
}

This is my code for the Vehicle class:

public class Vehicle {
    int numWheels;
    int ID;
    String name;
}

Solution

  • First of all Garage extends Vehicle makes no sense. I'm assuming it's a mistake. A Garage is not a Vehicle.

    In Garage you can implement clone as :

    @Override
    protected Object clone() {
        Garage other = new Garage ();
        for (Vehicle v : this.array) {
            other.addVehicle((Vehicle)v.clone());
        }
        return other;
    }
    

    Then you have to implement clone() in the Vehicle class hierarchy.