Qus:    What do you understand by copy constructor in Java?
Feb 16, 2022 17:23 Java 1 Answers Views: 1331 SANTHOSH
Prev Next
Answers (1)
Rlwf0 Rlwf0 Feb 17, 2021 18:23
Answer:   There is no copy constructor in java. However, we can copy the values from one object to another like copy constructor in C++.
There are many ways to copy the values of one object into another in java. They are:
o By constructor
o By assigning the values of one object into another
o By clone() method of Object class
In this example, we are going to copy the values of one object into another using java constructor.
1. //Java program to initialize the values from one object to another
2. class Student6{
3. int id;
4. String name;
5. //constructor to initialize integer and string
6. Student6(int i,String n){
7. id = i;
8. name = n;
9. }
10. //constructor to initialize another object
11. Student6(Student6 s){
12. id = s.id;
13. name =s.name;
14. }
15. void display(){System.out.println(id+" "+name);}
16.
17. public static void main(String args[]){
18. Student6 s1 = new Student6(111,"Karan");
19. Student6 s2 = new Student6(s1);
20. s1.display();
21. s2.display();
22. }
23. }
Test it Now
Output:
111 Karan
111 Karan

Post Your Answer
Guest User

Not sure what solution is right for you?

Choose the right one for you.
Get the help of the experts and find a solution that best suits your needs.


Let`s Connect