Lec-8b Copy Constructor
Lec-8b Copy Constructor
PROGRAMMING
LECTURE # 8B: COPY
CONSTRUCTOR
Department of CS
1 BSSE-2
Hitec University Taxila
COPY CONSTRUCTOR
When we pass object reference to the constructor
then it’s called copy constructor.
Copy constructor in java is a constructor which
copy the value of one object to another.
A copy constructor in programming, particularly in
languages like C++ and Java, is used to create a
new object as a copy of an existing object. It's
essentially a special constructor that allows you to
create a new object by copying the values of
another object of the same class.
2
BASIC ALGORITHM FOR IMPLEMENTING A COPY
CONSTRUCTOR IN JAVA:
Create a Class: Define a class for which you want to
implement the copy constructor. For example, let's
consider a class named MyClass.
Define Instance Variables: Declare the instance
variables that represent the state of objects of your class.
These variables define the attributes or properties of
objects.
Create a Constructor: Define a constructor to initialize
the instance variables of the class. This constructor will be
used to create objects of the class.
Implement the Copy Constructor: Define another
constructor that takes an object of the same class as a
parameter. This constructor will be used to create a copy
of an existing object. Inside this constructor, assign the
values of the instance variables of the parameter object to 3
the corresponding instance variables of the current object.
PROGRAM 1
package Xyz;
public class Student
{
private int roll;
private String name;
//constructor to initialize roll number and name of the student
Student(int rollNo, String sName)
{
roll = rollNo;
name = sName;
}
4
PROGRAM 1
//copy constructor
Student(Student student)
{
System.out.println("\n---Copy Constructor Invoked---");
roll = student.roll;
name = student.name;
}
5
PROGRAM 1
//method to return roll number
int printRoll()
{
return roll;
}
//Method to return name of the student
String printName()
{
return name;
}
6
PROGRAM 1
//class to create student object and print roll number and name of the student
package Xyz;
public class Xyz
{
public static void main(String[] args)
{
Student student1 = new Student(101, “ali");
System.out.println("Roll number of the first student: "+ student1.printRoll());
System.out.println("Name of the first student: "+ student1.printName());