Search code examples
javaclone

Is it possible to use clon() method without overriding it


I am having some trouble with my teacher, we have to master the concepts of java in aabout one month, he is saying that following is possible:

so in Java every class is inheriting from Object class, this class provides us with methods like protected Object clone() for example: Now let´s say that we have class Car

// later in main:

Car mycar=new Car();
//he is saying now that  following is possible:
Car yourCar=(Car) mycar.clone();

but every article online says that this is not possible, even when i try to compile it it's not possible, firstly because the method is protected and secondly because it would throw an exeption

is there something that I am missing ?


Solution

  • Yes, you can use .clone() without overriding it as long as the class implements Cloneable.

    Here's an example:

    class Car implements Cloneable {
      String name;
      public Car(String n) {
        name = n;
      }
    
      public static void main(String[] args) throws Exception {
        Car c1 = new Car("Lightning McQueen");
        Car c2 = (Car) c1.clone();
        System.out.println(c2.name);
      }
    }
    

    Here's the description of the default behavior of clone() when the class implements Cloneable but does not override clone():

    this method creates a new instance of the class of this object and initializes all its fields with exactly the contents of the corresponding fields of this object, as if by assignment; the contents of the fields are not themselves cloned. Thus, this method performs a "shallow copy" of this object, not a "deep copy" operation.