×

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

Check if the given array is mirror inverse in Java

The primary objective is to check whether the given array is mirror inverse or not. The values and position of the specified array are switched, and a duplicate array is created....

3 minutes read.

Operators in Java

There is a good operator environment provided by Java. These operators are divided into four different groups i.e. arithmetic, bitwise, relational, and logical. There are other operators also available to...

7 minutes read.

Java Thread Priority in Multithreading

As we realise, java, being object-situated, works inside a multithreading climate in which the string scheduler relegates the processor to a string in light of the need for a string....

6 minutes read.

Hierarchy of operators in Java

Operators are the most frequently used terminology in any area of programming, and it helps in various approaches to efficiently solve daily life problems by computer programming. The simple addition of...

4 minutes read.

Ramanujan Number or Taxicab Number in Java

In this section, we will discuss what a Ramanujan number (also known as a Hardy-Ramanujan number) is and how to use a Java programme to determine if a given integer...

3 minutes read.

Exception Handling Program in Java

Exception Handling Program in Java Exception means something that is abnormal. In Java, an exception is treated as a problem that disrupts the normal flow of the program. An exception leads...

7 minutes read.

File Operation in Java

In Java, a file is an Abstract data type. These are used to store the data which is related. Files are named storage locations. With a file we can perform...

7 minutes read.

Literals in Java

In this article we acknowledge ourselves about the term literals in java, types of literals and an example to each of them. Literal Literal refers to any constant value that can be...

4 minutes read.

Static vs Non-Static in Java

A static method can access and update the value of a static data member. The static keyword is mostly used in Java for memory management. The static keyword can be...

6 minutes read.

Trimorphic numbers in Java

Wondered what the Trimorphic number is!! In this article, you can learn about what a Trimorphic number is referred to as and how to find whether a number is trimorphic...

3 minutes read.

Java Code Optimization

We encounter the idea of optimization while working on any Java application. It is essential that the code we write is not only clear and error-free but also optimized, meaning...

9 minutes read.

Buffer reader to read string in Java

The Buffered Reader class of Java is used to read the stream of characters from the input stream. Program to read string using Buffer reader import java.io.*; class  Demo {   public static void main(String...

3 minutes read.

Java FileNotFoundException

FileNotFoundException is another exception class accessible in the java.io bundle. The exemption happens when we attempt to get to that document which isn't accessible in the framework. It is a checked...

5 minutes read.

The Maximum Rectangular Area in a Histogram in Java

Continuous bars should be used to form the largest possible rectangle. We'll assume in the interest of convenience that each bar's width is 1. Naive Approach In this method, each bar will be...

6 minutes read.

Java Integer compareUnsigned() method

The compareUnsigned() method of Integer class compares two int objects numerically by treating the values as unsigned. Syntax public static int compareUnsigned(int x , int y) Parameters The parameters ‘x’ and ‘y’ represent the...

1 minute read.

Java Set Interface

We use set when we don't want to allow duplicate entries. All Set implementations do not allow duplicates. HashSet: This class stores its elements in hash tables. It uses the hashCode()...

3 minutes read.

Java Math abs() Method

The abs() method of Math class returns the absolute value of the argument where the argument can be int, double, float, long. Syntax public static int abs(int a) public static float abs(float a) public...

2 minutes read.

String vs StringBuilder

String vs StringBuilder In this section, we will discuss the comparison between Java String and StringBuilder class. String In Java, a string is treated as an object that represents a sequence of characters....

4 minutes read.

Selection Sort in Java

Selection Sort in Java Selection sort is also a simple sorting algorithm that works by repeatedly finding the minimum element from the unsorted portion of the input array, and placing it...

5 minutes read.

Java Math floorMod() Method

The floorMod() method of Math class returns the floor modulus of the specified arguments. It firstly divides the dividend and divisor and then returns an integer that is equal to...

1 minute read.