×

Java copy constructor Example

Java provides the copy constructor much like C++ does. However, it is produced by default in C++. While we define our own copy constructor in Java. With an example, we will learn about Java's copy constructor in this section.

Constructor

The only distinction between a constructor and a method in Java is that the constructor uses the same name as the class. It is utilised to make a class instance. When we create an object belonging to the class, it is immediately called. No return type is present. Keep in mind that a constructor cannot be static, synchronised, final, or abstract. A constructor is inaccessible to us. When called, it takes up some memory space.

Two types of constructors

  • The Default constructor
  • The parameterized constructor

Java additionally allows the copy constructor in addition to the first two. Let's get into it in more detail.

Why is a copy constructor necessary?

We occasionally run across situations when we need to make an exact duplicate of an already-existing class object. Another requirement is that any changes we make to the copy must not be reflected in the original and vice versa. Java offers you notion of a copy constructor for such circumstances.

Copy constructor

A copy constructor in Java is a unique kind of constructor that makes use of an existing object belonging to the identical Java class to produce a new object. A duplicate of an already-existing class object is what is returned.

The final field can be given a value, but when using the clone() function, this is not possible. If we wish to make the duplicate of an existing object, we use it. Comparatively speaking, it is simpler to implement than the clone() technique.

Note: It can be inherited by the subclasses. When cloning an object of a child class using the copy function Object() { [native code] }, we run into the casting issue if we attempt to initialize it with a parent class reference.

Copy Constructor usage

If we want, we may utilise the copy constructor to:

  • Make a duplicate of an object with several fields.
  • Make a thorough copy of the bulky items.
  • Utilization of the Object.clone() function should be avoided.

Benefits of the Copy Constructor

  • A field that has been marked as final may be modified by the copy function Object() { [native code] }.
  • Typecasting is not necessary.
  • The more fields an item contains, the easier it is to use.
  • Because of this, adding a variable towards the class is simple. One area alone needs to be changed: the copy function Object() { [native code] }.

Establishing a Copy Constructor

Use the instructions underneath to generate a copy constructor in Java:

  • Make a constructor that takes a parameter that is an object belonging to the same class.
public class Fun  
{   
private double cost;   
private String title;   
//The copy constructor  
public Fun(Fun fun)   
{   
//The getters  
}   
}  
  • In the instance that was just generated, copy every field (variable) object.
public class Fun 
{   
private double cost;   
private String title;   
//The copy constructor  
public Fun(Fun fun)   
{  
// each filed copying   
this.cost = fun.cost; //The getter  
this.title = fun.title; //The getter  
}   
}

An illustration of copy constructor

public class Fun 
{  
private double fcost;  
private String ftitle;  
// constructor to set the student's name and roll number
Fruit(double fCost, String fName)  
{   
fprice = fPrice;  
ftitle = fTitle;  
}  
// establishing a copy function Object() { [native code] }
Fun(Fun fun)  
{  
System.out.println("\nFollowing use of the Copy Constructor:\n");  
fcost = fun.fcost;  
ftitle = fun.ftitle;  
}  
// developing a system that returns the cost of the fruit
double showCost()  
{  
return fcost;  
}  
// developing a system that returns the cost of the fruit


String showTitle()  
{  
return ftitle;  
}  
// creating an object for students in the class that prints their names and roll numbers
public static void main(String args[])  
{  
Fun f3 = new Fun(299, "Roman Reigns funs");  
System.out.println("First fun's title:"+ f3.showTitle());  
System.out.println("First fun's cost:"+ f3.showCost());  
// supplying the copy constructor with the parameters
Fun f4 = new Fun(f3);  
System.out.println("Second fun’s name: "+ f4.showTitle());  
System.out.println("Second fruit’s Cost: "+ f4.showCost());  
}  
} 

Output:

First fun's title: Roman Reigns funs
First fun's cost: 299.0


Following use of the Copy Constructor:


Second fun’s title: Roman Reigns funs
Second fun’s cost: 299.0

Related Topics

Construct the Largest Number from the Given Array in Java

In this section, we will create a Java programme that will enable you to locate the greatest integer in an array. The programme will begin comparing the array's numbers with...

3 minutes read.

Various operations on HashSet in Java

In this article, you will be acknowledged about what is a HashSet in java and what are its operations in java programming language. The HashSet is a crucial part of...

3 minutes read.

Java Long Keyword

Long is a primitive data type in Java. To initilize variables, we implement the long keyword. It can also be applied to techniques. A 64-bit two's complement integer can put...

3 minutes read.

Java Math log1p() Method

The log1p() method of Math class returns the natural logarithmic sum for the specified double argument and 1. Its value is much closer to result of ln(1 + x). Syntax: public static...

2 minutes read.

Magic Square in Java

A square with numbers is referred to as a magic square. The numbers in a magic square of order n are arranged to ensure that the sum of all of...

4 minutes read.

Java Enum

Enumerations are used in programming languages to represent collections of named constants. For instance, the four suits in a deck of playing cards might represent four iterators named Club, Diamond,...

3 minutes read.

Upcasting in Java

To know what is Upcasting in Java we should first equip ourselves about what is casting or type casting in Java. Casting The process of providing or replacing a reference variable of...

3 minutes read.

Java File Input Stream

Java makes use of stream ideas to speed up input and output processes. All packages of input and output streams are contained in java.io.package. Stream: A stream is nothing more...

5 minutes read.

Java Control Statements

Control Statements: Control statements in Java can also be referred to as decision-making while dealing with different problems. Control statements are helpful to sort out the flow of the program or...

7 minutes read.

Annotations in Java

Annotations in Java Java Annotations are metadata about the source code. They do not have any direct effect on the execution of the java program. Annotations in Java were introduced in...

4 minutes read.

Heap Implementation in Java

The root node or parent node of a Java heap is compared to its left and right offspring, and the children are then ordered in line with the comparison.Assuming that...

9 minutes read.

Java Clone Array

We frequently need to copy an array to back up its original components. We have a few unique numbers and strings, including Armstrong numbers, palindrome numbers, and palindrome strings. To...

4 minutes read.

Java Instanceof Keyword

To determine whether an object is an instance of the supplied type in Java, use the instanceof operator (class or subclass or interface). The type of comparison in java differentiates the...

4 minutes read.

Java Math nextAfter() Method

The nextAfter() method of Math class returns the floating-point value adjacent to the first argument in direction of the second argument. Syntax: public static double nextAfter (double start, double direction)public static float...

2 minutes read.

Mutable and Immutable in Java

Java is a programming language in which everything is treated as an object. Its procedures and functions are centred around objects because it is an object-oriented programming language. Mutable and...

6 minutes read.

POJO in Java

Plain old Java Object, in short, is called POJO in Java. POJO is an everyday object that is not subject to any specific limitations. We can use POJO in any Java...

3 minutes read.

Round Robin Scheduling Program in Java

A CPU scheduling technique is known as Round Robin (RR). Additionally, network schedulers employ it. It was created specifically for a time-sharing system. The temporal slicing scheduling algorithm is another...

4 minutes read.

Java Boolean compare() method

The compare() method of Java Boolean class compares the specified Boolean values and returns a positive 1 or negative 1 or zero integer value based on the result. Syntax public static int...

2 minutes read.

How to reverse a linked list in java

The process of reversing a linked list in Java will be covered in this section. One of the most common questions in interviews is about reversing a linked list. If...

11 minutes read.

How to avoid deadlock in java

Deadlock: A deadlock is an event that never going to occur. In java, deadlock is just a part of the multithreading. It is an environment that allows us to run multiple...

4 minutes read.