Site icon DataFlair

Copy Constructor in Java with Examples

java copy constructor

Free Java courses with 37 real-time projects - Learn Java

In C++ there is a concept of copy constructor. Similarly, Java also supports Copy constructors but the difference is that in C++ the copy constructor is created by default while in Java we have to create the copy constructor on our own. In this article, we will see how to create a copy constructor and why it is necessary in our programs.

What are Constructors in Java?

Before learning about copy constructors, we need to understand the concept of constructors. Constructors are special methods that have the same name as the class. Using constructors we can initialize global variables. Constructors do not have any return type. They are called automatically when an object is declared for that class. Constructors occupy space according to the variables present in them.

Types of Java Constructors:

1. Default Constructor in Java

Constructors which do not have a parameter list are known as default constructor.

Example of Default Constructor:

package com.DataFlair.CopyConstructor;
public class DefaultConstructor
{ 
    DefaultConstructor()
    {
        System.out.println("Object Created, so Constructor Called");
    }    
    public static void main(String args[])
    {   
        DefaultConstructor d=new DefaultConstructor(); 
    }
}

The output of the above code:

Object Created, so Constructor Called

2. Parameterized Constructor in Java

These are the Constructors which have a parameter list in it.

Example of Parameterized Constructor:

package com.DataFlair.CopyConstructor;
public class ParameterConstructor
{
    int id;  
    String name;
    ParameterConstructor(int i,String n){  
    id = i;  
    name = n;  
    }  
    void display()
    {
        System.out.println(id+" "+name);
    }
    public static void main(String args[]){   
    ParameterConstructor P = new ParameterConstructor(1,"Arka");
    P.display();  
   }  
}  

The output of the above Code:

1 Arka

Other than these two Constructors, Java also supports Copy Constructors, we will discuss it in detail now.

What is a Copy Constructor in Java?

Technology is evolving rapidly!
Stay updated with DataFlair on WhatsApp!!

As the name suggests, Copy Constructor is used to create a copy of a previously existing object present in the class. It is a special type of constructor that returns a duplicate copy of another object.
In C language, the copy constructor is declared automatically, but in Java, we have to create the method separately.

Why is it required to use Java Copy Constructor?

The main purpose of a copy constructor is to create a copy of an object. This helps in the reusability of code. Sometimes we might be required to use a copy of an object with minor changes, without reflecting it to the original one, for such scenarios a copy constructor is essential.

Creating a Copy Constructor in Java

The steps to create a copy constructor are as follows:

Step 1: We have to create a constructor that takes an object as a parameter. Make sure that the object belongs to the same class.

public class Interns  
{   
private int ID;   
private String name;    
public Interns(Interns interns)//copy constructor  
{   
//getters  
}   
}  

Step 2: Using getters copy each variable of the copied object to the new instances.

public class Interns  
{   
private int ID;   
private String name;    
public Interns(Interns interns)//copy constructor  
{   
this.ID=interns.ID;//getters  
this.name=interns.name;//getters
}   
}

How to Copy Mutable Type data in Java?

To copy mutable type data, we have to create a deep copy instead of a shallow copy which we did in the previous example.

Let us understand this with a code:

Code to understand Mutable data with copy constructor:

public class Interns
{
        private int ID;
        private String name;
        private Date InternDate;//Mutable Data

        public Interns( Interns interns )
        {
                this.roll = interns.id;
                this.name = interns.name;
                this.InternDate = new Date(interns.InternDate.getTime());//Deep Copy
        }
}

Code to Explain the working of Copy Constructor:

package com.DataFlair.CopyConstructor;
public class Interns
{  
    private int ID;   
    private String Name; 
    Interns(int id, String name)//parameterized constructor
    {
        ID=id;
        Name=name;
    }
    Interns(Interns interns)//copy constructor  
    {   
        System.out.println("The Copy Constructor Starts here");
        ID=interns.ID;//getters  
        Name=interns.Name;//getters
    }   
    int showID()
    {
        return ID;
    }
    String showName()
    {
        return Name;
    }
    public static void main(String[] args)
    {
        Interns I=new Interns(1,"Arka");
        System.out.println("ID of Intern: "+ I.showID()+ " Name of Intern:"+ I.showName());
        Interns IC=new Interns(I);
        System.out.println("ID of Intern: "+ I.showID()+ " Name of Intern:"+ I.showName());
    }
}

The Output of the above Program:

ID of Intern: 1 Name of Intern:Arka
The Copy Constructor Starts here
ID of Intern: 1 Name of Intern:Arka

Advantages of Using Copy Constructor in Java

To understand the advantage of a copy constructor, let us try to copy an object without using a copy constructor.

Code for creating a copy of an object without using Copy Constructor:

package com.DataFlair.CopyConstructor;
public class Intern
{
     private int ID;
     private String name;
  Intern(int id, String Name)
  { 
    ID = id;
    name= Name;
  }
  
  Intern()
  {  
  }
  int printID()
  {
    return ID;
  }
  String printName()
  {
    return name;
  }
  public static void main(String[ ] args)
  {
    Intern I1 = new Intern(1, "Arka");
    System.out.println("ID of Intern: "+ I1.printID());
    System.out.println("Name of Intern: "+ I1.printName());

    Intern I2 = new Intern();
    I2.ID= I1.ID;
    I2.name= I1.name;

    System.out.println("Copied ID of Intern: "+ I2.printID());
    System.out.println("Copied Name of Intern: "+ I2.printName());
}
}

The output of the above code:

ID of Intern: 1
Name of Intern: Arka
Copied ID of Intern: 1
Copied Name of Intern: Arka

So, we can clearly see that the size of the code increased considerably for only 2 variables. Now, imagine if there are 50 such variables how hard it will be to copy each variable separately. So, we can see why a copy constructor is an important concept to write optimal code.

Best Practices for Copy Constructors

When crafting copy constructors, here are some valuable guidelines to consider:

Difference Between Java Copy Constructor and Clone() Method:

Clone() is also a method using which we can create a duplicate copy of a pre-existing object. But using a clone method is more difficult compared to a copy constructor, due to the following reasons:

1. The clone method may throw an exception if the cloneable is not imported properly. Handling an exception is an extra task. While the Copy Constructor does not throw any such exceptions.

2. Using Clone() we cannot assign values to variables that are declared final. As we all know by now that copy constructor allows us to change the value of final variables.

3. In Clone() method typecasting is required, while in the copy constructor typecasting is not required.

Inheritance Issues in Java Copy Constructor:

One very big disadvantage of Copy Constructor is that the subclasses of the parent class which contains the copy constructor, cannot access the copy constructor. The program will give a casting error when we try to compile it.

Code explaining the Problem with inheritance and copy constructor:

package com.DataFlair.CopyConstructor;
import java.util.List;

public class TechWriter extends Interns
{
private List<Interns> Articles;
public TechWriter(TechWriter techwriter)
{
            super(techwriter.ID, techwriter.name);
            this.Articles = Articles.stream().collect(Collectors.toList());
}
}

The above code will give an error, as the compiler will not be able to recognize the variables ID and name. To fix this we have to typecast the variable with the subclass.

For Example:

Interns clone = new TechWriter((Techwriter)interns);

We can avoid typecasting by adding a new inherited method to both classes.

Code explaining how to avoid type casting in case of inherited copy constructor:

public class Interns
{
public Interns copy()
{
            return new Interns(this);
      }
}
 
public class Techwriter extends Interns
{
@Override
      public Interns copy() 
{
            return new Techwriter(this);
      }
}

Quiz on Java Copy Constructor

Time limit: 0

Quiz Summary

0 of 15 Questions completed

Questions:

Information

You have already completed the quiz before. Hence you can not start it again.

Quiz is loading…

You must sign in or sign up to start the quiz.

You must first complete the following:

Results

Quiz complete. Results are being recorded.

Results

0 of 15 Questions answered correctly

Your time:

Time has elapsed

You have reached 0 of 0 point(s), (0)

Earned Point(s): 0 of 0, (0)
0 Essay(s) Pending (Possible Point(s): 0)

Categories

  1. Not categorized 0%
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  1. Current
  2. Review / Skip
  3. Answered
  4. Correct
  5. Incorrect
  1. Question 1 of 15
    1. Question

    Which of the following raises errors while using copy constructor ?

    Correct
    Incorrect
  2. Question 2 of 15
    2. Question

    Which of the following is the correct syntax of creating a copy constructor ?

    Correct
    Incorrect
  3. Question 3 of 15
    3. Question

    class User {

    String a ;

    String b;

    public void User ( String x , String y )

    {

    a = this.x;

    b = this.y;

    }

    User(User u)

    {

    this.a = u.a;

    this.b = u.b;

    }

    void Display ( )

    {

    System.out.println(a + “ “ + b );

    }

    }

    class Main {

    public static void main ( String args [ ] )

    {

    User obj1 = new User( “ DataFlair ” , ” Webservices ” );

    User obj2 = new User(obj1);

    obj2.display();

    }

    }

    What is the output of the program ?

    Correct
    Incorrect
  4. Question 4 of 15
    4. Question

    What is the return function of a copy constructor ?

    Correct
    Incorrect
  5. Question 5 of 15
    5. Question

    class Constructor {

    public Constructor ( )

    {

    System.out.println(“Constructor is invoked”);

    }

    void method()

    {

    System.out.println(“Method is invoked”);

    }

    }

    class Main {

    public static void main ( String args [ ] )

    {

    Constructor c = new Constructor();

    Constructor obj = new Constructor(c);

    c.method();

    }

    }

    What will be the output of the program ?

    Correct
    Incorrect
  6. Question 6 of 15
    6. Question

     class Main {

    private int a;

    Main ( int x )

    {

    a = this.x;

    }

    Main ( Main m )

    {

    a = m.x;

    }

    void value ( )

    {

    System.out.println(a+a);

    System.out.println(2*a);

    }

    public static void main ( String args [ ] )

    {

    Main m = new Main ();

    Main m2 = new Main(m);

    m2.value();

    }

    }

    What is the output of the program ?

    Correct
    Incorrect
  7. Question 7 of 15
    7. Question

    Which of the following is used to clone an Object ?

    Correct
    Incorrect
  8. Question 8 of 15
    8. Question

    class Main {

    int x,y;

    public Main ( int i , int j )

    {

    x = this.i;

    y = this.j;

    }

    Main ( int i , int j )

    {

    x = i;

    y = j;

    }

    Void calculate ( )

    {

    return x+y;

    }

    public static void main ( String args [ ] )

    {

    Main m1 = new Main();

    Main m2 = new Main(m1);

    m2.calculate(2,5);

    }

    }

    What is the error in the program ?

    Correct
    Incorrect
  9. Question 9 of 15
    9. Question

     class Function {

    private String message = “DataFlair”;

    Function ( )

    {

    System.out.println(message);

    }

    Function ( )

    {

    System.out.println(message+” ” + “Webservices”);

    }

    public static void main ( String args [ ] )

    {

    Function f1 = new Function();

    Function f2 = new Function(f1);

    }

    }

    What will be the output of the program ?

    Correct
    Incorrect
  10. Question 10 of 15
    10. Question

    Which of the following is supported in C but not in Java ?

    Correct
    Incorrect
  11. Question 11 of 15
    11. Question

    class Sample {

    String text;

    public void Sample ( String a )

    {

    text = this,a;

    }

    Sample ( Sample s )

    {

    text = s.a;

    }

    void show()

    {

    System.out.println(a);

    }

    }

    class Main {

    public static void main ( String args [ ] )

    {

    Sample obj = new Sample();

    Sample object2 = new Sample(obj);

    object2.show(“DataFlair”);

    }

    }

    What is the output of the program ?

    Correct
    Incorrect
  12. Question 12 of 15
    12. Question

    class Maths {

    int r;

    public Maths ( int a ) 

    {

    r = this.a;

    }

    Maths ( Maths m )

    {

    r = m.a;

    }

    void calculate {

    System.out.println(“Diameter = “ + 2r);

    System.out.println(“Area = “ + 3.14*r*r);

    }

    }

    class Main {

    public static void main ( String args [ ] )

    {

    Maths m1 = new Maths();

    Maths m2 = new Maths(m1);

    m2.r = 10;

    }

    }

    What is the output of the program ?

    Correct
    Incorrect
  13. Question 13 of 15
    13. Question

    Which of the following is not true about copy constructor ?

    Correct
    Incorrect
  14. Question 14 of 15
    14. Question

    class Demo {

    String name;

    Demo ( String message )

    name = this.message;

    }

    Demo ( Demo d )

    {

    name = d.message;

    }

    }

    class Main {

    public static void main ( String args [ ] )

    {

    Demo d = new Demo(“Welcome”);

    }

    }

    What is the output of the program ?

    Correct
    Incorrect
  15. Question 15 of 15
    15. Question

    class Sum {

    int x , y ;

    Sum ( int a , int b )

    {

    x = a;

    y = b;

    }

    Sum( Sum s )

    {

    x = s.a;

    y = s.b;

    }

    void plus ( )

    {

    return x+y;

    }

    }

    class Main {

    public static void main ( String args [ ] )

    {

    Sum object1 = new Sum();

    object1.plus(1,2);

    Sum Object2 = new Sum(object1);

    object2.a = 3;

    object2.b = 4;

    object2.plus();

    }

    }

    What is the output of the program ?

    Correct
    Incorrect

Common Use Cases for Copy Constructors

Copy constructors offer a versatile mechanism for object duplication in various situations. Here are a few examples:

Conclusion:

Java constructors are one of the most important concepts when it comes to writing effective code. In this article, we saw how a copy constructor can be declared manually in Java. We also saw the importance, advantages and disadvantages of using copy constructors.

Exit mobile version