Header Ads

Copy Constructor in Java | How to Create Copy Constructor in Java | Object Oriented Programming Java

 

In Java copy constructor is a special constructor that allows you to create a new object by copying the properties of an existing object. Here is an Example of how to create a copy constructor in Java

1. Create Student Class

2. Create Two Constructor Parameter and Copy Constructor

3. Create Two Object

Program Source Code

package Student.com;

import java.util.Scanner;

public class Student {

private int rollno;

private String name;

//Create Constructor

public Student(int rno,String n) {

this.rollno = rno;

this.name = n;

}

//Create Copy Constructor

public Student(Student student) {

this.rollno = student.rollno;

this.name = student.name;

}

public void Display() {

System.out.println("Rollno :"+this.rollno);

System.out.println("Name :"+this.name);

}

public static void main(String[] args) {

// TODO Auto-generated method stub

Scanner ins = new Scanner(System.in);

System.out.println("Enter Rollno :");

int rollno = ins.nextInt();

System.out.println("Enter Name:");

String name = ins.next();

Student objstd = new Student(rollno,name);

System.out.println("---Orignal Data of Student---");

objstd.Display();

Student copy_objstd = new Student(objstd);

System.out.println("---Copy Constructor Data of Student---");

copy_objstd.Display();

}

}

Explanation 

In the Example above we have created a “Student” 

Class with two constructor. 

One is Parameter constructor and other is copy constructor. 

The copy constructor takes an object of the same

class as its parameter and initializes the new

object with the same values as the existing object

To use the copy constructor you can create new object of the “Student” type and pass an existing object as its parameter


Related Video





No comments

Powered by Blogger.