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

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

Single Number 3 LeetCode Solution - The Coding Shala

LeetCode - Number of Good Pairs Solution - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Java Method Overloading - The Coding Shala