Copy Constructor
There is no copy constructor in java. But we can copy the value one object to another object like copy constructor in C++.
There are many way to create a copy constructor in java.
- By constructor
- By assigning value from one object to other
- Using clone() Method of object class.
Example Copy Constructor by Constructor
Example:
//Java program to copy constructors
class Student{
int id;
String name;
int age;
Student(int i, String n, int a ){
id = i;
name = n;
age= a;
}
Student(Student s){
id = s.id;
name = s.name;
age= s.age;
}
void display(){System.out.println(id+" "+name+" "+age);}
class const{
public static void main(String args[]){
Student s1 = new Student(111, “Karan”, 25);
Student s2 = new Student(s1);
s1.display();
s2.display();
}
}
Output:
111,Karan,25
111,Karan,25
Example Copy Constructor without constructor or using object value
Example:
//Java program to copy constructors
class Student{
int id;
String name;
int age;
Student(int i, String n, int a ){
id = i;
name = n;
age= a;
}
Student(){ }
class const{
public static void main(String args[]){
Student s1 = new Student(111, “Karan”, 25);
Student s2 = new Student();
s2.id=s1.id;
s2.name=s1.name;
s2.age=s1.age;
s1.display();
s2.display();
}
}
Output:
111,Karan,25
111,Karan,25