Java Copy Constructor - The Coding Shala

Home >> Learn Java >> Java Copy Constructor

Java Copy Constructor

Java does not support copy constructor by default but we can create our own constructor to copy the values from one object to another.
Java Copy Constructor - The Coding Shala

Example of Copy Constructor in Java

The following is an example of java copy constructor:
public class Student{
    int id;
    String name;
        System.out.println("Default Constructor");
    Student(int id, String name){ = id; = name;
        System.out.println("Constructor with parameters");
    //creating copy Constructor
    Student(Student s){ =; =;
        System.out.println("Copy Constructor");
    void Display(){
        System.out.println(id+" "+name);
    public static void main(String[] args){
       Student s1 = new Student(1, "Akshay");
       //copying Constructor
       Student s2 = new Student(s1); //passing object as argument 
       //can also copy object with calling Constrctor 
       Student s3 = new Student(); =; =;

Constructor with parameters
1 Akshay
Copy Constructor
1 Akshay
Default Constructor
1 Akshay

Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.


Popular Posts from this Blog

LeetCode - Crawler Log Folder Solution - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala

Shell Script to find sum, product and average of given numbers - The Coding Shala

First Unique Character in a String Java - The Coding Shala

Add two numbers in Scala - The Coding Shala