InterviewSolution
Saved Bookmarks
| 1. |
Copy Constructor in Java |
|
Answer» The main usage of the copy CONSTRUCTOR is to create an object of a class by initializing it with another object of the same class. A copy constructor in Java is not available by default like in C++, but needs to be explicitly created. A program that DEMONSTRATES a copy constructor in Java is GIVEN as follows: class Employee { int empNo; String name; int salary; Employee(int eNo, String n, int sal) { empNo = eNo; name = n; salary = sal; } Employee( Employee e) { empNo = e.empNo; name = e.name; salary = e.salary; } void print() { System.out.println("Employee Number = " + empNo); System.out.println("Name = " + name); System.out.println("Salary = " + salary); } } public class Demo { public static void main(String args[]) { Employee emp1 = new Employee(1, "John", 25000); Employee emp2 = new Employee(emp1); emp1.print(); emp2.print(); } }The output of the above program is as follows: Employee Number = 1 Name = John Salary = 25000 Employee Number = 1 Name = John Salary = 25000 |
|