In Java, a constructor
method or subroutine is just like a normal function, and the only variation is that the constructor method has the same name as the class name.
It helps to create an instance of the class and call it explicitly. This special type of method does not return anything.
A constructor that accepts at least one argument is said to be a parameterized constructor. To initialize an object, the initial values have to be passed as arguments public Car(String _model, String _color)
to the constructor method, as shown below.
A copy constructor is a variant of the constructor method of a class that creates an exact copy of an existing object. When someone wants to copy
a complicated object or copy with some edits, we use a copy constructor. It allows us to do either a deep or shallow copy of that object. A copy constructor can be called in various scenarios. For instance:
clone()
method.In Java, the default copy constructor is not available, unlike in C/C++. So, it should be defined by the user before use.
The following is the declaration syntax of the copy constructor in Java.
The following code snippet illustrates the demo of the copy constructor defined in the class Car
. We have parameterized as well as copy constructors here.
public Car(String _model, String _color)
takes car model
and color
as an argument to initialize the Car c1
instance on line 24
. On line 15
, copy constructor public Car(Car c)
will be called explicitly to initialize Car c2
on line 26
.
// How copy cotructor called explicitlypublic class Car{public String model;public String color;// Parameterized Constructorpublic Car(String _model, String _color){this.model = _model;this.color = _color;}//Copy Constructorpublic Car(Car c){System.out.println("Copy Constructor Called");this.model = c.model;this.color = c.color;}public static void main(String[] args){Car c1 = new Car("Toyota Fortuner SIGMA 4x4","Phantom Brown");// here a copy constructor is being called.Car c2 = new Car(c1);System.out.println("\t#1");System.out.println(c1.model + " " + c1.color); // prints "Toyota Fortuner SIGMA 4x4 Phantom Brown"System.out.println(c2.model + " " + c2.color); // prints "Toyota Fortuner SIGMA 4x4 Phantom Brown"c2.model = "Toyota Fortuner V 4x4";c2.color = "Grey Metallic";System.out.println("\t#2");System.out.println(c1.model + " " + c1.color); // prints "Toyota Fortuner SIGMA 4x4 Phantom Brown"System.out.println(c2.model + " " + c2.color); // prints "Toyota Fortuner V 4x4 Grey Metallic"}}