{"id":77690,"date":"2020-04-13T15:46:46","date_gmt":"2020-04-13T10:16:46","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=77690"},"modified":"2020-04-13T15:46:46","modified_gmt":"2020-04-13T10:16:46","slug":"java-copy-constructor","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/java-copy-constructor\/","title":{"rendered":"Java Copy Constructor &#8211; Advantages and Examples"},"content":{"rendered":"<p><strong>Welcome back to Techvidvan Java Tutorial Series.<\/strong><\/p>\n<p>Sometimes, a developer falls into a situation where he needs to create a duplicate but exact copy of an existing object of a class. He wants to create a separate copy but the exact one of the existing objects such that the changes made in the duplicate copy won\u2019t reflect on the original object or vice-versa.<\/p>\n<p>Java makes this possible by providing a concept of Copy Constructors.<strong> Java copy constructors<\/strong> are the special type of Constructors in Java that we use to create a duplicate of the existing object of a class. In this article, we will learn how to create and use a java copy constructor with examples.<\/p>\n<h3>What is a Java Copy Constructor?<\/h3>\n<p>A Copy Constructor in Java is a special type of constructor that is used to create a new object using the existing object of a class that we have created previously. It creates a new object by initializing the object with the instance of the same class.<\/p>\n<p>The Java Copy Constructor provides a copy of the specified object by taking the argument as the existing object of the same class. Java does not implicitly provide the facility of a Copy constructor as in C language. But, we can define it by copying the values of one object to another object.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/04\/copy-constructor-in-java.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-78286\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/04\/copy-constructor-in-java.jpg\" alt=\"copy constructor in java\" width=\"640\" height=\"387\" \/><\/a><\/p>\n<h3>Creating a Copy Constructor in Java<\/h3>\n<p>To create a copy constructor in Java, we need to first declare a constructor that takes an object of the same type as a parameter. For example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">public class Student\n{\n        private int roll ;\n        private String name;\n\n        \/\/ Declaring a copy constructor by passing the parameter as the class\n        public Student( Student student )\n        {\n        }\n}<\/pre>\n<p>After declaring a copy constructor, we need to copy each field of the input object of the class into the new object. For example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">public class Student\n{\n        private int roll;\n        private String name;\n\n        \/\/ Copying each field of the existing object into the newly created object\n        public Student( Student student )\n        {\n                this.id = student.roll;\n                this.name = student.name;\n        }\n}<\/pre>\n<p>From the above code snippet, we created a shallow copy of the object. It will work fine as we are using the immutable and primitive types, i.e int and String.<\/p>\n<p><strong>But what if we have mutable types in our code?<\/strong><\/p>\n<p>If there is a mutable data type in Java program, then we can create a deep copy rather than a shallow copy so that the newly created object becomes independent of the existing object. Let\u2019s see an example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">public class Student\n{\n        private int roll;\n        private String name;\n        private Date admissionDate;\n\n        public Student( Student student )\n        {\n                this.roll = student.id;\n                this.name = student.name;\n                this.admissionDate = new Date(student.admissionDate.getTime());\n        }\n}<\/pre>\n<h3>Example of Copy Constructor in Java<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.techvidvan.copyconstructor;\npublic class Student \n{\n  private int roll;\n  private String name;\n\n  \/\/constructor to initialize roll number and name of the student\n  Student(int rollNo, String sName)\n  { \n    roll = rollNo;\n    name = sName;\n  }\n\n  \/\/copy constructor\n  Student(Student student)\n  {\n    System.out.println(\"\\n---Copy Constructor Invoked---\");\n    roll = student.roll;\n    name = student.name;\n  }\n  \/\/method to return roll number\n  int printRoll()\n  {\n    return roll;\n  }\n\/\/Method to return name of the student\n  String printName()\n  {\n    return name;\n  }\n  \/\/class to create student object and print roll number and name of the student\n\n  public static void main(String[] args)\n  {\n    Student student1 = new Student(101, \"Sneha\");\n    System.out.println(\"Roll number of the first student: \"+ student1.printRoll());\n    System.out.println(\"Name of the first student: \"+ student1.printName());\n\n    \/\/passing the parameter to the copy constructor\n    Student student2 = new Student(student1);\n\n    System.out.println(\"\\nRoll number of the second student: \"+ student2.printRoll());\n    System.out.println(\"Name of the second student: \"+ student2.printName());\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">Roll number of the first student: 101<br \/>\nName of the first student: Sneha<br \/>\n&#8212;Copy Constructor Invoked&#8212;<br \/>\nRoll number of the second student: 101<br \/>\nName of the second student: Sneha<\/div>\n<h3>Advantages of Copy Constructor in Java<\/h3>\n<p>The Copy constructor in java has several advantages that encourage every Java developer to use it in the Java code. Let\u2019s discuss these advantages of Copy constructor in Java:<\/p>\n<ol>\n<li>The Copy constructor is easier to use when our class contains a complex object with several parameters.<\/li>\n<li>Whenever we want to add any field to our class, then we can do so just by changing the input to the constructor.<\/li>\n<li>One of the most crucial importance of copy constructors is that there is no need for any typecasting.<\/li>\n<li>Copy Constructors allow us to change the fields declared as final.<\/li>\n<li>Using a copy constructor, we can have complete control over object creation.<\/li>\n<\/ol>\n<h3>Creating Duplicate objects without using a Copy Constructor<\/h3>\n<p>We can also create a copy of an object without using a copy constructor, just by assigning the values of one object into the other object. See the below example to understand this:<\/p>\n<p><strong>Code to create a copy of an object without using a copy constructor<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.techvidvan.copyconstructor;\npublic class Student \n{\n  private int roll;\n  private String name;\n\n  \/\/constructor to initialize roll number and name of the student\n  Student(int rollNo, String sName)\n  { \n    roll = rollNo;\n    name= sName;\n  }\n  \n  Student()\n  {\t\n  }\n\n  \/\/method to return roll number\n  int printRoll()\n  {\n    return roll;\n  }\n  \/\/Method to print name\n  String printName()\n  {\n    return name;\n  }\n  \/\/class to create student object and print roll number and name of the student\n\n  public static void main(String[ ] args)\n  {\n    Student student1 = new Student(101, \"Sneha\");\n    System.out.println(\"Roll number of the first student: \"+ student1.printRoll());\n    System.out.println(\"Name of the first student: \"+ student1.printName());\n\n    Student student2 = new Student();\n    student2.roll= student1.roll;\n    student2.name= student1.name;\n\n    System.out.println(\"\\nRoll number of the second student: \"+ student2.printRoll());\n    System.out.println(\"Name of the second student: \"+ student2.printName());\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">Roll number of the first student: 101<br \/>\nName of the first student: Sneha<br \/>\nRoll number of the second student: 101<br \/>\nName of the second student: Sneha<\/div>\n<h3>Java Copy Constructor vs. clone() method in Java<\/h3>\n<p>We can also use the clone() method to get a copy of an object from an existing object of the class. But the Copy constructor is better to use than the clone() method because of the following reasons:<\/p>\n<p>1. It is easier to implement and use a copy constructor than the <strong>clone() method<\/strong>. Because when using the clone() method to create an object, we need to implement the <strong>Cloneable interface<\/strong> in our program and also need to handle the <strong>CloneNotSupportedException<\/strong>. In the Copy constructor, there is no need for such complex things in our program.<\/p>\n<p>2. We need to typecast the object returned by the<strong> clone()<\/strong> method to the appropriate type. There is no need of <strong>typecasting<\/strong> the objects while using the copy constructor.<\/p>\n<p>3. When we use a clone() method, we can not assign a value to a<strong> final field.<\/strong> But, we can do so in the copy constructor.<\/p>\n<h3>Inheritance Issues<\/h3>\n<p>The subclasses or the child classes can not extend the Copy constructors in Java. If we try to initialize a child object from a parent class reference, we will get a casting error.<\/p>\n<p>To understand this issue, let&#8217;s first create a subclass of Student and its copy constructor:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">public class EngineeringStudent extends Student\n{\nprivate List&lt;Student&gt; performanceReport;\n    \t\/\/ ... other constructors\n \n    \tpublic EngineeringStudent(EngineeringStudent engineeringStudent)\n{\n        \t\tsuper(enggStudent.roll, enggStudent.name, enggStudent.admissionDate);\n        \t\tthis.performanceReport = performanceReport.stream().collect(Collectors.toList());\n   \t}\n}<\/pre>\n<p>Then, we declare a Student variable and instantiate it with the constructor of the EngineeringStudent class:<\/p>\n<p>Student student = new EngineeringStudent(101, &#8220;Shreya&#8221;, admissionDate, performanceReports);<\/p>\n<p>Since the reference type is of Student class, we need to typecast it to the EngineeringStudent type so that we can use the copy constructor of the Student class:<\/p>\n<p>Student clone = new EngineeringStudent((EngineeringStudent) student);<\/p>\n<p>We may get a <strong>ClassCastException<\/strong> at runtime if the input object is not of the EngineeringStudent class type. One way to avoid casting in the copy constructor is to create a new inheritable method for both classes. For example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">public class Student\n{\npublic Student copy()\n{\n        \t\treturn new Student(this);\n    \t}\n}\n \npublic class EngineeringStudent extends Student\n{\n@Override\n    \tpublic Student copy() \n{\n        \t\treturn new EngineeringStudent(this);\n    \t}\n}<\/pre>\n<h3>Conclusion<\/h3>\n<p>Java copy constructor is used to create a copy of the current object of the class. We can create a copy constructor explicitly by passing it an argument as the class name whose object we want to create.<\/p>\n<p>In this tutorial, we studied what a copy constructor in Java is and how can we create it in Java. We also discussed some issues regarding the copy constructor in java and how we can recover from those issues.<\/p>\n<p>Everything in this article was explained with example. This article will assure you that you strengthen your concepts in Java Copy Constructor.<\/p>\n<p><strong>Do share your feedback in the comment section.<\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Welcome back to Techvidvan Java Tutorial Series. Sometimes, a developer falls into a situation where he needs to create a duplicate but exact copy of an existing object of a class. He wants to&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":78286,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[183],"tags":[2352,2353,2354],"class_list":["post-77690","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","tag-copy-constructor-in-java","tag-java-copy-constructor","tag-java-copy-constructor-example"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.4 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Java Copy Constructor - Advantages and Examples - TechVidvan<\/title>\n<meta name=\"description\" content=\"Java Copy constructor - Learn what is copy constructor in java with examples. Learn advantages of copy constructor &amp; its difference from clone() method\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/java-copy-constructor\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Java Copy Constructor - Advantages and Examples - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Java Copy constructor - Learn what is copy constructor in java with examples. Learn advantages of copy constructor &amp; its difference from clone() method\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/java-copy-constructor\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2020-04-13T10:16:46+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/04\/copy-constructor-in-java.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"640\" \/>\n\t<meta property=\"og:image:height\" content=\"387\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"7 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Java Copy Constructor - Advantages and Examples - TechVidvan","description":"Java Copy constructor - Learn what is copy constructor in java with examples. Learn advantages of copy constructor & its difference from clone() method","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/techvidvan.com\/tutorials\/java-copy-constructor\/","og_locale":"en_US","og_type":"article","og_title":"Java Copy Constructor - Advantages and Examples - TechVidvan","og_description":"Java Copy constructor - Learn what is copy constructor in java with examples. Learn advantages of copy constructor & its difference from clone() method","og_url":"https:\/\/techvidvan.com\/tutorials\/java-copy-constructor\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2020-04-13T10:16:46+00:00","og_image":[{"width":640,"height":387,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/04\/copy-constructor-in-java.jpg","type":"image\/jpeg"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"7 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/java-copy-constructor\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-copy-constructor\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Java Copy Constructor &#8211; Advantages and Examples","datePublished":"2020-04-13T10:16:46+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-copy-constructor\/"},"wordCount":1008,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-copy-constructor\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/04\/copy-constructor-in-java.jpg","keywords":["Copy Constructor in Java","Java Copy Constructor","Java Copy Constructor Example"],"articleSection":["Java Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/java-copy-constructor\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/java-copy-constructor\/","url":"https:\/\/techvidvan.com\/tutorials\/java-copy-constructor\/","name":"Java Copy Constructor - Advantages and Examples - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-copy-constructor\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-copy-constructor\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/04\/copy-constructor-in-java.jpg","datePublished":"2020-04-13T10:16:46+00:00","description":"Java Copy constructor - Learn what is copy constructor in java with examples. Learn advantages of copy constructor & its difference from clone() method","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-copy-constructor\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/java-copy-constructor\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/java-copy-constructor\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/04\/copy-constructor-in-java.jpg","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/04\/copy-constructor-in-java.jpg","width":640,"height":387,"caption":"copy constructor in java"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/java-copy-constructor\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Java Copy Constructor &#8211; Advantages and Examples"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/77690","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=77690"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/77690\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/78286"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=77690"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=77690"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=77690"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}