0 votes
11 views
What do you understand by copy constructor in Java?
in Education by (48.2k points)

1 Answer

0 votes
What do you understand by copy constructor in Java?

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:

By constructor

By assigning the values of one object into another

By clone() method of Object class

In this example, we are going to copy the values of one object into another using java constructor.

//Java program to initialize the values from one object to another  

class Student6{  

    int id;  

    String name;  

    //constructor to initialize integer and string  

    Student6(int i,String n){  

    id = i;  

    name = n;  

    }  

    //constructor to initialize another object  

    Student6(Student6 s){  

    id = s.id;  

    name =s.name;  

    }  

    void display(){System.out.println(id+" "+name);}  

   

    public static void main(String args[]){  

    Student6 s1 = new Student6(111,"Karan");  

    Student6 s2 = new Student6(s1);  

    s1.display();  

    s2.display();  

   }  

}  

Test it Now

Output:

111 Karan

111 Karan
by (48.2k points)

Related questions

0 votes
1 answer 8 views
0 votes
1 answer 9 views
9 views asked Nov 17, 2020 in Education by Editorial Staff (48.2k points)
0 votes
1 answer 10 views
10 views asked Nov 19, 2020 in Education by Editorial Staff (48.2k points)
0 votes
1 answer 9 views
0 votes
1 answer 13 views
0 votes
1 answer 11 views
0 votes
1 answer 13 views
0 votes
1 answer 13 views
0 votes
1 answer 15 views
0 votes
1 answer 14 views
0 votes
1 answer 12 views
12 views asked Dec 6, 2020 in Technology by JackTerrance (186k points)
0 votes
1 answer 13 views
0 votes
1 answer 8 views
0 votes
1 answer 13 views
0 votes
1 answer 19 views
0 votes
1 answer 19 views
0 votes
1 answer 17 views
0 votes
1 answer 19 views
0 votes
1 answer 15 views
15 views asked Nov 5, 2020 in Technology by JackTerrance (186k points)
0 votes
1 answer 12 views
...