Java Copy Constructor ExampleLike C++, Java also supports the copy constructor. But in C++ it is created by default. While in Java we define copy constructor our own. In this section, we will learn the copy constructor in Java with an example. ConstructorIn Java, a constructor is the same as a method but the only difference is that the constructor has the same name as the class name. It is used to create an instance of the class. It is called automatically when we create an object of the class. It has no return type. Remember that a constructor cannot be abstract, final, synchronized, and static. We cannot override a constructor. It occupies some space in memory when it is called. Types of Constructor
Except for the above two constructors, Java also supports the copy constructor. Let's discuss it in detail. Why copy constructor is required?Sometimes, we face a problem where we required to create an exact copy of an existing object of the class. There is also a condition, if we have made any changes in the copy it should not reflect in the original one and vice-versa. For such cases, Java provides the concept of a copy constructor. Copy ConstructorIn Java, a copy constructor is a special type of constructor that creates an object using another object of the same Java class. It returns a duplicate copy of an existing object of the class. We can assign a value to the final field but the same cannot be done while using the clone() method. It is used if we want to create a deep copy of an existing object. It is easier to implement in comparison to the clone() method. Note: It cannot be inherited by the subclasses. If we try to initialize a child class object from a parent class reference, we face the casting problem when cloning it with the copy constructor.Use of Copy ConstructorWe can use the copy constructor if we want to:
Advantages of Copy Constructor
Creating a Copy ConstructorTo create a copy constructor in Java, follow the steps given below:
Example of Copy ConstructorCopyConstructorExample.java Output: Name of the first fruit: Ruby Roman Grapes Price of the first fruit: 399.0 After invoking the Copy Constructor: Name of the second fruit: Ruby Roman Grapes Price of the second fruit: 399.0 Copy Constructor Vs clone() MethodBoth the copy constructor and the clone() method are used to create a copy of an existing object of the class. But the use of copy constructor is easier and better in comparison to the clone() method because of the reasons given below:
Next TopicWhy We Use Static Class in Java |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India