Creating Copy Constructors in Java

JavaJavaBeginner
Practice Now

Introduction

In this lab, we will learn how to create copy constructors in Java. Copy constructors are used to create a new object using the values of an existing object. The copy constructors can be used to create shallow as well as deep clones. We will create copy constructors for simple classes and classes with referenced types.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ProgrammingTechniquesGroup(["`Programming Techniques`"]) java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/BasicSyntaxGroup(["`Basic Syntax`"]) java(("`Java`")) -.-> java/StringManipulationGroup(["`String Manipulation`"]) java(("`Java`")) -.-> java/SystemandDataProcessingGroup(["`System and Data Processing`"]) java/ProgrammingTechniquesGroup -.-> java/scope("`Scope`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/inner_classes("`Inner Classes`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/classes_objects("`Classes/Objects`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/class_attributes("`Class Attributes`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/class_methods("`Class Methods`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/encapsulation("`Encapsulation`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/modifiers("`Modifiers`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("`OOP`") java/BasicSyntaxGroup -.-> java/identifier("`Identifier`") java/BasicSyntaxGroup -.-> java/comments("`Comments`") java/BasicSyntaxGroup -.-> java/data_types("`Data Types`") java/BasicSyntaxGroup -.-> java/operators("`Operators`") java/BasicSyntaxGroup -.-> java/output("`Output`") java/StringManipulationGroup -.-> java/strings("`Strings`") java/SystemandDataProcessingGroup -.-> java/system_methods("`System Methods`") subgraph Lab Skills java/scope -.-> lab-117400{{"`Creating Copy Constructors in Java`"}} java/inner_classes -.-> lab-117400{{"`Creating Copy Constructors in Java`"}} java/classes_objects -.-> lab-117400{{"`Creating Copy Constructors in Java`"}} java/class_attributes -.-> lab-117400{{"`Creating Copy Constructors in Java`"}} java/class_methods -.-> lab-117400{{"`Creating Copy Constructors in Java`"}} java/encapsulation -.-> lab-117400{{"`Creating Copy Constructors in Java`"}} java/modifiers -.-> lab-117400{{"`Creating Copy Constructors in Java`"}} java/oop -.-> lab-117400{{"`Creating Copy Constructors in Java`"}} java/identifier -.-> lab-117400{{"`Creating Copy Constructors in Java`"}} java/comments -.-> lab-117400{{"`Creating Copy Constructors in Java`"}} java/data_types -.-> lab-117400{{"`Creating Copy Constructors in Java`"}} java/operators -.-> lab-117400{{"`Creating Copy Constructors in Java`"}} java/output -.-> lab-117400{{"`Creating Copy Constructors in Java`"}} java/strings -.-> lab-117400{{"`Creating Copy Constructors in Java`"}} java/system_methods -.-> lab-117400{{"`Creating Copy Constructors in Java`"}} end

Create a Simple Class

Create a simple Student class with a name and GPA field. We will use this class to create a copy constructor.

class Student {
	private String name;
	private double gpa;

	// parameterized constructor
	Student(String name, double gpa) {
		this.name = name;
		this.gpa = gpa;
    }
}

Create a Copy Constructor for a Simple Class

Create a copy constructor for the Student class. The copy constructor should take an object of the class as input and should initialize the fields by using the values of the input object.

// Copy constructor
Student(Student s) {
	this.name = s.getName();
	this.gpa = s.getGpa();
}

// getters
public String getName() {
	return name;
}

public double getGpa() {
	return gpa;
}

Create an Object and Clone

Create an object of the Student class and then create a clone of that object using the copy constructor. Change the name of the original object and print out the names of both objects to see if the cloned object was affected.

Student s = new Student("John", 3.5);
Student s2 = new Student(s);

s.setName("Sarah");

System.out.println("Original: " + s.getName());
System.out.println("Clone: " + s2.getName());

Create a Class with Referenced Types

Create a Student class that contains a referenced type (Address) as a field. We will use this class to demonstrate the difference between shallow and deep cloning.

class Student {
	private String name;
	private double gpa;
	private Address address;

	// parameterized constructor
	Student(String name, double gpa, Address address) {
		this.name = name;
		this.gpa = gpa;
		this.address = address;
	}
}

class Address {
	private int postalCode;

	Address(int postalCode) {
		this.postalCode = postalCode;
    }
}

Create a Shallow Copy Constructor

Create a shallow copy constructor for the Student class. The shallow copy constructor should only assign references to the referenced type fields.

Student(Student s) {
	this.name = s.getName();
	this.gpa = s.getGpa();
	this.address = s.getAddress();
}

Demonstrate Shallow Cloning

Create a Student object and then a clone using the shallow copy constructor. Change the postal code of the original object's address and print out both postal codes to show that the cloned object is affected by changes to the original.

Student s = new Student("John", 3.5, new Address(12345));
Student s2 = new Student(s);

s.getAddress().setPostalCode(54321);

System.out.println("Original: " + s.getAddress().getPostalCode());
System.out.println("Clone: " + s2.getAddress().getPostalCode());

Create a Deep Copy Constructor

Create a deep copy constructor for the Student class. The deep copy constructor should create new objects for referenced type fields.

Student(Student s) {
	this.name = s.getName();
	this.gpa = s.getGpa();
	this.address = new Address(s.getAddress().getPostalCode());
}

// getters
public Address getAddress() {
	return address;
}

Demonstrate Deep Cloning

Create a Student object and then a clone using the deep copy constructor. Change the postal code of the original object's address and print out both postal codes to show that the cloned object is not affected by changes to the original.

Student s = new Student("John", 3.5, new Address(12345));
Student s2 = new Student(s);

s.getAddress().setPostalCode(54321);

System.out.println("Original: " + s.getAddress().getPostalCode());
System.out.println("Clone: " + s2.getAddress().getPostalCode());

Summary

In this lab, we learned how to create copy constructors in Java. Copy constructors can be used to create deep and shallow clones of objects. We also compared copy constructors with the clone() method and discussed inheritance issues with copy constructors. Creating copy constructors is an elegant and simple way to clone objects.

Other Java Tutorials you may like