Java Tutorial: Copy Constructor in Java

In our previous discussion, we have come to know how to pass an object reference to a method. In the same way, we can pass the reference to a constructor to initialize the instance variables of another object of the same class. You can use the same value of the instance variables of the object which is sent to the constructor. One object is copied to other objects. Let’s check out this Java Tutorial Copy Constructor in Java language.

Java Tutorial Copy Constructor in Java

Advantages of using Copy Constructor

There are several use cases where Copy Constructors works well with respect to other constructors in Java.

As we know objects can be cloned in Java using clone() method. But copying object using clone() is not flexible and extensible, doesn’t work fine as well.

The first problem is that no constructor call happens when the object is being cloned. As a result, it is your responsibility, as a writer of the clone method, to make sure all the members have been properly set. Here is an example of where things could go wrong.

Consider a class keeping track of the total number of objects of that type, using a static int member. In the constructors you would increase the count. However, if you clone the object, since no constructor is called, the count will not truly reflect the number of objects!

Further, if the class has final fields, these can’t be given a value in the clone method. This leads to problems with properly initializing the object’s final fields. If the final field is referring to some internal state of the object, then the cloned object ends up sharing the internal state and this surely is not correct for mutable objects.

Disadvantages of using Copy Constructor

As one object is the exact replica of another, any change in the first one it will inadvertently change the values of the instance variables of other. So you have to be careful and better not to declare copy constructor as public. Otherwise, during inheritance, it doesn’t satisfy Open-Closed Principle (OCP). The OCP, by Bertrand Meyer, states that software entities should be open for extension, but closed for modifications.

Program for Copy Constructor

class Employee{
  String employeeName;
  String address;
  int age;
  double salary;

/*Default Constructor */

  Employee(){
    employeeName = "Platini";
    address = "France";
    age = 45;
    salary = 120500.92;
  }

/* Parameterized Constructor */

  Employee(String empName,String addr,int ag,double sal){
    employeeName = empName;
    address = addr;
    age = ag;
    salary = sal;
  }

/* Copy Constructor  */

  Employee(Employee emp){
    employeeName = emp.employeeName;
    address = emp.address;
    age = emp.age;
    salary = emp.salary;
  }

  void showDetails(){
    System.out.println("Employee's Name: "+employeeName);
    System.out.println("Employee's Address: "+address);
    System.out.println("Employee's Age: "+age);
    System.out.println("Employee's Salary: "+salary);
  }

}

class ConstructorDemo{
  public static void main(String args[]){
    System.out.println("Employee Details");
    System.out.println("----------------");
    Employee employee1 = new Employee();
    employee1.showDetails();

    System.out.println("----------------");

    String employeeName = "John";
    String address = "Los Angles";
    int age = 25;
    double salary = 34503.92;
    Employee employee2 = new Employee(employeeName,address,age,salary);
    employee2.showDetails();

    System.out.println("----------------");

    Employee employee3 = new Employee();
    employee3.showDetails();

    System.out.println("----------------");

    Employee employee4 = new Employee(employee2);
    employee4.showDetails();

    System.out.println("----------------");

    Employee employee5 = new Employee(employee3);
    employee5.showDetails();

  }
}

Output

Java Tutorial Copy Constructor in Java

Explanation of the Java Code & Output

Please carefully observe the code marked in red, basically, in the Employee class, you will find the syntax how to declare copy constructor. We have created two more objects employee 4 and employee5 which are a copy of employee2 and employee3 respectively. From the output, it is clearly visible that instance variables of employee4 are having the same value as the values of instance variables of employee2. Same is true for employee5.

Next, we will see how to use the keyword “static” in Java. Check out more useful tutorials and definitive guidelines on Java programming here.

2 comments

  1. Constructor is basically function which is called automatically when the instance of that class is created.so,differentiate them from user defined function they have same name of the class.

  2. package com.cxt.java.core;

    /** A JAVA APPLICATION THAT DEMONSTRATE THE USE OF ‘COPY CONSTRUCTOR’ IN JAVA. *
    * @author Shrikant.Kale
    */
    public class Galaxy {

    private double fMass;
    private final String fName;

    /**
    * This is the only method which changes the state of a Galaxy
    * object. If this method were removed, then a copy constructor
    * would not be provided either, since immutable objects do not
    * need a copy constructor.
    */
    public void setMass( double aMass ){
    fMass = aMass;
    }

    public double getMass() {
    return fMass;
    }

    public String getName() {
    return fName;
    }

    public Galaxy (double aMass, String aName) {
    fMass = aMass;
    fName = aName;
    }

    /**
    * Copy constructor.
    */
    public Galaxy(Galaxy aGalaxy) {
    this(aGalaxy.getMass(), aGalaxy.getName());
    //no defensive copies are created here, since
    //there are no mutable object fields (String is immutable)
    }

    /**
    * Alternative style for a copy constructor, using a static newInstance
    * method.
    */
    public static Galaxy newInstance(Galaxy aGalaxy) {
    return new Galaxy(aGalaxy.getMass(), aGalaxy.getName());
    }

    /**
    * Test harness.
    */
    public static void main (String args[]){

    Galaxy m101 = new Galaxy(15.0, “M101”);

    Galaxy m101CopyOne = new Galaxy(m101);

    m101CopyOne.setMass(25.0);
    System.out.println(“M101 mass: ” + m101.getMass());
    System.out.println(“M101Copy mass: ” + m101CopyOne.getMass());

    Galaxy m101CopyTwo = Galaxy.newInstance(m101);
    m101CopyTwo.setMass(35.0);
    System.out.println(“M101 mass: ” + m101.getMass());
    System.out.println(“M101CopyTwo mass: ” + m101CopyTwo.getMass());

    }
    }

Leave a Reply

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