I saw an example that try to explain inheritance in Java. The class Employee, which is the base class, has three instance variables and three constructors. it is as follows:
public class Employee{
private String name;
private int id;
public Employee(){
name = " No Name!";
id = 00100;
}
public Employee(String n, int i){
name = n;
id = i;
}
public Employee (Employee originalObject){
name = originalObject.name;
id = originalObject.id;
}
My question is : What’s the point of the third constructor? and how it accepts an argument with the same type, Employee ,of the class that we are still working on ? The program has already an empty constructor and another one that passes String for name and int for id, so why there is an extra one that does no much more than the previous two constructors ?
It looks like the third constructor is intended to make a copy of an existing
Employeeobject.You could probably do the same thing with:
but that presumes that there are “get” methods for every property. It’s easier to implement one constructor like that, and then call:
Then, if the properties of
Employeeneed to change, you would only have to change the copy constructor in one place.