DEV Community

Vignesh . M
Vignesh . M

Posted on

COPY CONSTRUCTOR

A copy constructor in Java is a constructor that creates a new object by copying the fields of another object of the same class.

syntax:

ClassName(ClassName obj) {
    // copy fields from obj
}

Enter fullscreen mode Exit fullscreen mode

program:

public class Student {
    int id;
    String name;

    // Parameterized constructor
    Student(int id, String name) {
        this.id = id;
        this.name = name;
    }

    // Copy constructor
    Student(Student s) {
        this.id = s.id;
        this.name = s.name;
    }

    void display() {
        System.out.println("ID: " + id + ", Name: " + name);
    }

    public static void main(String[] args) {
        Student s1 = new Student(1022, "kumar");
        Student s2 = new Student(s1); // Using copy constructor

        s1.display();
        s2.display();
    }
}
Enter fullscreen mode Exit fullscreen mode

output:
ID: 1022, Name: kumar
ID: 1022, Name: kumar

Top comments (0)