class
Shallow Copy example
In this example we shall show you how to create a shallow copy of a class. To create a shallow copy of a class we have performed the following steps:
- We have created a class,
Car
that has a String field and a getter and setter method for it. It also has a constructor using its String field. - We have also created a class,
Person
, that implements the Cloneable interface in order to override itsclone()
API method. It has aCar
field and a String field, getters for both fields and a setter method for the String field. It also has a constructor using both fields, where it initializes theCar
field with a given String and sets the value of the String field to another given field. - In
clone()
method the super classe’sclone()
method is called, that is theclone()
method of Object. - We create a new instance of
Person
and using its getters we get the String field and the String field of itsCar
field. - We also create a clone object, using the
clone()
method ofPerson
. - We change the String field of clone object and the String field of
Car
field of the clone object. Both fields are changed in the clone object, whereas the original objects has held its initial value for its String field, and the String field of its low-level objectCar
has also changed,
as described in the code snippet below.
package com.javacodegeeks.snippets.core; public class ShallowCopy { public static void main(String[] args) { //Original Object Person person = new Person("Person-A", "Civic"); System.out.println("Original : " + person.getN() + " - " + person.getC().getN()); //Clone as a shallow copy Person person2 = (Person) person.clone(); System.out.println("Clone (before change): " + person2.getN() + " - " + person2.getC().getN()); //change the primitive member person2.setN("Person-B"); //change the lower-level object person2.getC().setN("Accord"); System.out.println("Clone (after change): " + person2.getN() + " - " + person2.getC().getN()); System.out.println("Original (after clone is modified): " + person.getN() + " - " + person.getC().getN()); } } class Person implements Cloneable { //Lower-level object private Car carObject; private String name; public Car getC() { return carObject; } public String getN() { return name; } public void setN(String s) { name = s; } public Person(String s, String t) { name = s; carObject = new Car(t); } @Override public Object clone() { //shallow copy try { return super.clone(); } catch (CloneNotSupportedException e) { return null; } } } class Car { private String carName; public String getN() { return carName; } public void setN(String s) { carName = s; } public Car(String s) { carName = s; } }
Output:
Original : Person-A - Civic
Clone (before change): Person-A - Civic
Clone (after change): Person-B - Accord
Original (after clone is modified): Person-A - Accord
This was an example of how to create a shallow copy of a class in Java.