Why do we need copy constructor and when should we use copy constructor in java -
i going through copy constructors, have gone through links in stack on flow , others well. not clear on following points.
- why need copy constructor
- when need copy constructor
i mean exact situation or scenario need use copy constructor. can 1 explain example or point out links can go through , understand them in clear.
following links have gone through understanding of copy constructor.
http://www.programmerinterview.com/index.php/java-questions/how-copy-constructors-work/
https://deepeshdarshan.wordpress.com/2013/12/05/copy-constructors-in-java/
the second link explains 'why' , 'where' copy constructor used. still not clear on it.
below class employee.java
package com.test; /** * @author avinashd * */ public class employee { private string rollno; private string name; //constructor public employee(string rollno, string name){ this.rollno = rollno; this.name = name; } //copy constructor public employee(employee employee){ this.rollno = employee.rollno; this.name = employee.name; } public string getrollno() { return rollno; } public void setrollno(string rollno) { this.rollno = rollno; } public string getname() { return name; } public void setname(string name) { this.name = name; } }
copy constructor used create , exact copy of object same values of existing object.
say example have employee values rollno: 1
, name: avinash
. copy constructor create similar object values rollno: 1
, name: avinash
. both 2 different objects , changes values of on object not affect object.
the question here
when have constructor such
public employee(string rollno, string name){ this.rollno = rollno; this.name = name; }
to create object. can call same constructor create object. why need call copy constructor.when need call ?. please explain
there 2 reasons using copy constructor instead of constructor passing parameters :
- when have complex object many attributes more simpler use copy constructor
- if add attribute class, change copy constructor take new attribute account instead of changing every occurence of other constructor
Comments
Post a Comment