
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Need and Usage of Copy Constructor in Java
A copy constructor is a parameterized constructor and it can be used when we want to copy the values of one object to another.
Example:
class Employee { int id; String name; Employee(int id, String name) { this.id = id; this.name = name; } Employee(Employee e) { id = e.id; name = e.name; } void show() { System.out.println(id + " " + name); } public static void main(String args[]) { Employee e1 = new Employee(001, "Aditya"); Employee e2 = new Employee(e1); e1.show(); e2.show(); } }
In the above code, e1 is passed as an argument to the second constructor. Thus values of e1 are copied into object e2.
Output:
1 Aditya 1 Aditya
Advertisements