×

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

AES 256 Encryption in Java

Now a days, security has grown in importance. Java programming supports a variety of encryption and hashing methods, which offers security for data transport and communication among various nodes. In...

4 minutes read.

StringBuffer in Java

StringBuffer in Java Similar to StringBuilder, the Java StringBuffer class is also used to create modifiable or mutable strings. The StringBuilder class is synchronized, i.e., thread-safe. Java StringBuffer ConstructorThe StringBuffer class has...

7 minutes read.

Java Image

For all other classes used for representing graphical images, Java's Image class serves as an abstract superclass. For images in Java, a specific form of object known as a BufferedImage...

4 minutes read.

Decagonal Numbers in Java

This section explains what is a decagonal number and how to write Java programmes that compute decagonal numbers. Both academics and Java programmer interviews regularly question about the Decagonal number...

3 minutes read.

Java program to count the occurrences of each character

The count of each character is the frequency of the characters. For example, the given String is “Programming”. In the given string, the count of the characters ‘P’ -1, ’r’-2,...

6 minutes read.

Classes and Objects in Java Example Programs

Classes and Objects in Java Example Programs Java is an Object-Oriented programming language, i.e., everything in Java is associated with objects and objects are associated with classes. The classes and objects...

5 minutes read.

Java vs Go

Java: Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say that...

4 minutes read.

Frugal number in Java

A frugal number is a positive integer with base b that has more digits than the number of prime factors it can be factored into (including exponents greater than 1)....

3 minutes read.

String to JSON in Java

Nowadays, receiving data in JSON String format rather than XML is quite frequent. Java does not transform JSON String to JSON Object when dealing with JSON String. However, using the...

3 minutes read.

Java Pi

What is Pi? There are many formulas in geometry that employ the Pi constant to calculate things like circumference, area, and volume. A circle's circumference divided by its diameter yields a...

3 minutes read.

Implementing Queue Using Array in Java

We can implement queue by using array in Java. The queue is a linear data structure, and the array is one of the simplest data structures. Before implementing a queue...

4 minutes read.

Sphenic Number in Java

In this section, we will learn what is a sphenic number is and show you how to write Java programmes to determine if a specific number are sphenic or not....

3 minutes read.

Java Exception Propagation

Java Exception Propagation When an exception is being thrown from the peak of the stack and not getting caught, it runs down the stack to the previous method, which is sitting...

3 minutes read.

Addition Program in Java

Addition Program in Java We can perform the addition (sum) of two or more numbers by using the arithmetic operator (+). To write an addition program in Java, one must understand...

3 minutes read.

Tree Implementation in Java

Introduction to Tree A non-linear, hierarchical data structure called a "tree" is made up of a number of nodes, each of which contains a values and a sequence of pointers to...

14 minutes read.

Java IO file not found exception

One of the exception classes offered by the java.io package is FileNotFoundException. An exception is raised when we attempt to access a file that isn't present in the system. It...

4 minutes read.

Java Try-Catch Block

Java Try Block The handling of the exceptions in a block of code is done with the help of java try block. It throws the code that is enclosed in a...

3 minutes read.

Java Command not found

Java Command not found error is displayed if Java is not installed on the computer or if the command prompt cannot find Java.exe to run the program. Our Java software...

3 minutes read.

Java Program to Add Digits Until the Number Becomes a Single Digit Number

We will develop Java programme that increase a number's digit count in order to reduce it to one. The issue is also known as the digit root problem. Example Consider the case where...

3 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.