Example
/**
* This program is used to copy the values one object into another object using constructor.
* @author w3schools
*/
public class CopyValuesConstructor {
int id;
String name;
CopyValuesConstructor(int id, String name){
System.out.println("Constructor called.");
this.id = id;
this.name = name;
}
//Copy value of one object into another.
CopyValuesConstructor(CopyValuesConstructor obj){
System.out.println("Constructor called for copying value.");
this.id = obj.id;
this.name = obj.name;
}
public static void main(String args[]){
//parameterized constructor call
CopyValuesConstructor obj1 = new CopyValuesConstructor(10, "w3schools");
//print values of object properties.
System.out.println("obj1 id = " + obj1.id);
System.out.println("obj1 name = " + obj1.name);
//Constructor call to copy the value of one object into other.
CopyValuesConstructor obj2 = new CopyValuesConstructor(obj1);
//print values of object properties.
System.out.println("obj2 id = " + obj2.id);
System.out.println("obj2 name= " + obj2.name);
}
} |
/**
* This program is used to copy the values one object into another object using constructor.
* @author w3schools
*/
public class CopyValuesConstructor {
int id;
String name;
CopyValuesConstructor(int id, String name){
System.out.println("Constructor called.");
this.id = id;
this.name = name;
}
//Copy value of one object into another.
CopyValuesConstructor(CopyValuesConstructor obj){
System.out.println("Constructor called for copying value.");
this.id = obj.id;
this.name = obj.name;
}
public static void main(String args[]){
//parameterized constructor call
CopyValuesConstructor obj1 = new CopyValuesConstructor(10, "w3schools");
//print values of object properties.
System.out.println("obj1 id = " + obj1.id);
System.out.println("obj1 name = " + obj1.name);
//Constructor call to copy the value of one object into other.
CopyValuesConstructor obj2 = new CopyValuesConstructor(obj1);
//print values of object properties.
System.out.println("obj2 id = " + obj2.id);
System.out.println("obj2 name= " + obj2.name);
}
}
Output
Constructor called.
obj1 id = 10
obj1 name = w3schools
Constructor called for copying value.
obj2 id = 10
obj2 name= w3schools |
Constructor called.
obj1 id = 10
obj1 name = w3schools
Constructor called for copying value.
obj2 id = 10
obj2 name= w3schools
Java interview questions on constructor