Java Copy Constructor - The Coding Shala
Home >> Learn Java >> Java Copy Constructor
Output:
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.
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
Comments
Post a Comment