Scanner class Methods in Java

Java - Copy Constructor

 Copy Constructor

In last post, we learnt about Parameterized constructor.The third type of constructor is Copy Constructor.

Sometimes a programmer wants to create an exact but separate copy of an existing object so that subsequent changes to copy should not alter the original or vice versa.This is made possible using copy constructor.

A Copy Constructor is a constructor that creates a new object using an existing object of the same class and initializes each instance variable of newly created object with corresponding instance variables of the existing object passed as arguments. This constructor takes a single argument of class type which contains the constructor.

Example:

Write a program in which we create a copy of an existing constructor Rectangle of class Rectangle. 

copy constructor example

In the above example,
  1. The first class "CopyConstructorDemo" is the main class.In which we created the object of  "Rectangle" class. The firstRect is the first object which invokes the regular constructor of Rectangle class. The secondRect is the second object but it invokes the copy constructor of the Rectangle class. 
  2. This first print statements prints the result of area method by using values of length =5 and breadth=6 as given in firstRect constructor. The second print statements prints the result of area method but it takes firstRect object as argument and hence length and breadth is initialized with values passed in firstRect.
  3. After the closing of class "CopyConstructorDemo" we created class "Rectangle". In this class we created first constructor to initialize the value of variable of class.
  4. The copy constructor is created which takes the object of rectangle class as an argument.It again initialized the variables to class variables.
  5. The area() method is to calculate and return area of Rectangle.
Note: We can write as many as classes within a class. But there can be only one public and main class in a file. Remember first class must be closed before writing other class.

Output:

copy constructor example

Keep coding !

Comments