• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Copy Constructor in Java | Deep Copy And Shallow Copy

August 13, 2018 by javainterviewpoint Leave a Comment

A Copy Constructor in Java is a special type of Constructor, which enables us to get a copy of an existing object. Copy Constructors can take only one parameter, which is a reference of the same class.

In this article lets understand what is copy constructor and its uses.
The Copy Constructor helps us overcome the design issues of the clone() method. Copy Constructor comes in handy when you want to copy an object which has a lot of attributes.

Before getting into the details of Copy Constructor in Java, let’s understand the advantages of Copy Constructor over Object.clone() method

Advantages of copy constructors over Object.clone()

  • Unlike clone() method, Copy Constructors will not force us to implement the Cloneable or Serializable interface
  • Copy Constructor in Java is much easier to use even when the object has complex attributes.
  • It gives us the complete control over object copy, we can even mix both Deep Copy and Shallow Copy for different attributes of the class.
  • clone() method throws CloneNotSupportedException whenever the class does not implement Cloneable interface, Copy Constructor will not be throwing these Exceptions.
  • Typecasting is required as the clone() method returns Object type, whereas Copy Constructor does not need such typecasting.
  • Copy Constructor will let us change the value of a final attribute whereas clone() method will throw compilation error when you try to change a final field.

Copy Constructor in Java

  • In the below code the Person class has two variables x and y, a constructor with two arguments and a copy constructor.
  • We have created a Person object p1 by passing the values to its constructor and Person object p2 by passing the p1 to the Copy Constructor.
  • Once when we try to print the value of both the object p1 and p2 we will get same result 1 & 2.
  • Now we have changed the value of p2.x -> 3 and p2.y ->4, since primitives are by default deep copied we can change the values.
  • When we print again we will get the value of 1 & 2 for p1 and 3 & 4 for p2.
package com.javainterviewpoint;

public class Person
{
    public int x;
    public int y;
    
    //Constructor with 2 parameters
    public Person(int x, int y)
    {
        super();
        this.x = x;
        this.y = y;
    }
    
    //Copy Constructor
    public Person(Person p)
    {
        this.x = p.x;
        this.y = p.y;
    }
    
    public static void main(String[] args)
    {
        Person p1 = new Person(1,2);
        
        Person p2 =  new Person(p1);
        
        System.out.println(p1.x + " " + p1.y); // prints "1 2"
        System.out.println(p2.x + " " + p2.y); // prints "1 2"
        
        p2.x = 3;
        p2.y = 4;

        System.out.println(p1.x + " " + p1.y); // prints "1 2"
        System.out.println(p2.x + " " + p2.y); // prints "3 4"
    }
}

Java Deep Copy of references

With Copy Constructors we can achieve both Shallow Copy and Deep Copy

If a class has any references to other objects as fields, then only references of those objects are copied into clone object, a fresh copy of those objects are not created.

We need to use the new operator inside the Copy Constructor for it to be deep copied.

Let’s understand importance of a new keyword in below scenario with an example

Shallow Copying

Person.java

package com.javainterviewpoint;

public class Person
{
    public int x;
    public int y;
    
    public Address address;
    //Constructor with 2 parameters
    
    public Person(int x, int y, Address address)
    {
        super();
        this.x = x;
        this.y = y;
        this.address = address;
    }
    
    //Copy Constructor
    public Person(Person p)
    {
        this.x = p.x;
        this.y = p.y;
        this.address = p.address; //Shallow Copying
    }

    public static void main(String[] args)
    {
        Address address = new Address("Chennai","TN");
        
        Person p1 = new Person(1,2,address);
        
        Person p2 =  new Person(p1);
        
        System.out.println("*** Before changes ***");
        System.out.println(p1.address.city+" "+p1.address.state); 
        System.out.println(p2.address.city+" "+p2.address.state);
        
        //Lets change the city and state of P2 object
        p2.address.city = "Banglore";
        p2.address.state = "Karnataka";
        
        System.out.println("*** After change ***");
        System.out.println(p1.address.city+" "+p1.address.state); 
        System.out.println(p2.address.city+" "+p2.address.state); 
    }
}

Address.java

package com.javainterviewpoint;

public class Address
{
    public String city;
    public String state;
    
    public Address(String city, String state)
    {
        super();
        this.city = city;
        this.state = state;
    }

    public Address(Address address)
    {
        this.city = address.city;;
        this.state = address.state;
    }
}

Output

*** Before changes ***
Chennai TN
Chennai TN
*** After change ***
Banglore Karnataka
Banglore Karnataka
  • The Person class we have two variable x , y and instance of Address class. We have created two objects p1 and p2 (through copy constructor)
  • We have changed the city and state of the cloned object p2, but it gets reflected in the original object p1 object also.
  • This is because shallow copying, the Address member of the both original object p1, cloned object p2 refers to the same memory location.

Deep Copying

Lets now change our implementation from shallow Copying to deep Copying.

package com.javainterviewpoint;

public class Person
{
    public int x;
    public int y;
    
    public Address address;
    //Constructor with 2 parameters
    
    public Person(int x, int y, Address address)
    {
        super();
        this.x = x;
        this.y = y;
        this.address = address;
    }
    
    //Copy Constructor
    public Person(Person p)
    {
        this.x = p.x;
        this.y = p.y;
        this.address = new Address(p.address); //Deep Copying
    }

    public static void main(String[] args)
    {
        Address address = new Address("Chennai","TN");
        
        Person p1 = new Person(1,2,address);
        
        Person p2 =  new Person(p1);
        
        System.out.println("*** Before changes ***");
        System.out.println(p1.address.city+" "+p1.address.state); 
        System.out.println(p2.address.city+" "+p2.address.state);
        
        //Lets change the city and state of P2 object
        p2.address.city = "Banglore";
        p2.address.state = "Karnataka";
        
        System.out.println("*** After change ***");
        System.out.println(p1.address.city+" "+p1.address.state); 
        System.out.println(p2.address.city+" "+p2.address.state); 
    }
}

We have used the new keyword to implement deep copying, now if we see the output of p1 and p2 object is different.

Output

*** Before changes ***
Chennai TN
Chennai TN
*** After change ***
Chennai TN
Banglore Karnataka

Other interesting articles which you may like …

  • Constructor in Java
  • Private Constructors in Java
  • Java Constructor Chaining with example
  • Java – Constructor in an Interface?
  • Constructor.newInstance() method
  • Parameterized Constructor in Java
  • Java 8 – Lambda Expressions
  • Java 8 – ForEach Example
  • Java 8 Default Methods in Interface
  • Multiple Inheritance in Java 8 through Interface
  • Java 9 – jdeprscan
  • Private Methods in Interfaces Java 9
  • Java Method Overloading Example
  • Java Constructor Overloading Example
  • Java this keyword | Core Java Tutorial
  • Java super keyword
  • Abstract Class in Java
  • Interface in Java and Uses of Interface in Java
  • What is Marker Interface
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • Java Autoboxing and Unboxing Examples
  • Use of Java Transient Keyword – Serailization Example
  • Use of static Keyword in Java
  • What is Method Overriding in Java
  • Encapsulation in Java with Example
  • Final Keyword in Java | Java Tutorial
  • Java Static Import
  • Java – How System.out.println() really work?
  • Java Ternary operator
  • Java newInstance() method

Filed Under: Core Java, Java, Java Interview Tagged With: Copy Constructor, Copy Constructor in Java, Copy Constructors

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·