![]() |
VOOZH | about |
A Copy Constructor in Java is a constructor that creates a new object by copying the values of an existing object of the same class. Unlike C++, Java does not provide a default copy constructor, so it must be explicitly defined by the programmer.
class ClassName {
ClassName(ClassName obj) {
// Copy data members
}
}
Example 1: Copying a Student Object
Original Object: Name: John Age: 20 Copied Object: Name: John Age: 20
Explanation: In this example, s1 is the original object created using the parameterized constructor. The statement Student s2 = new Student(s1); invokes the copy constructor, which copies the values of name and age from s1 to s2. As a result, s2 becomes a separate object containing the same data as s1.
Example 2: Copy Constructor with Complex Numbers
Copy constructor called (10.0 + 15.0i)
Explanation: In this example, c1 is created using the parameterized constructor. The statement Complex c2 = new Complex(c1); invokes the copy constructor, which copies the values of re and im from c1 to c2. The statement Complex c3 = c2; does not create a new object; it only copies the reference. Therefore, only the creation of c2 uses the copy constructor.
Example 3: Invalid Constructor Call
Output:
Now, in the above code, the line calling the function with the object c1 as the parameter will give the error as the type of the parameter in the constructors is of 'double' type while the passed content is of 'object' type.