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;
    
    Student(){
        System.out.println("Default Constructor");
    }
    
    Student(int id, String name){
        this.id = id;
        this.name = name;
        System.out.println("Constructor with parameters");
    }
    
    //creating copy Constructor
    Student(Student s){
        this.id = s.id;
        this.name = s.name;
        System.out.println("Copy Constructor");
    }
    
    void Display(){
        System.out.println(id+" "+name);
    }
    
    public static void main(String[] args){
       Student s1 = new Student(1, "Akshay");
       s1.Display();
       //copying Constructor
       Student s2 = new Student(s1); //passing object as argument 
       s2.Display();
       //can also copy object with calling Constrctor 
       Student s3 = new Student();
       s3.id = s1.id;
       s3.name = s1.name;
       s3.Display();
    }
}

Output:
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.

Comments

Popular Posts from this Blog

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

Add two numbers in Scala - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Goal Parser Interpretation LeetCode Solution - The Coding Shala

New Year Chaos Solution - The Coding Shala