Reputation: 1124
In the practice I am doing now I have 3 classes in the hierarchy: Employee (abstract class) Worker extends Employee Manager extends Employee
I have an additional class who uses those 3 classes: Factory.
I have to build now a method which adds an Employee e to an array of Employees. Attributes:
_emps - an array of type Employee. _numOfEmpes - indicates the number of employess in the array.
This is the code I wrote:
public boolean addEmployee(Employee e){
if (this._numOfEmps<MAX_EMPS)
{
this._emps[this._numOfEmps]=e;
return true;
}
return false;
}
The problem is that I think that by the row:
this._emps[this._numOfEmps]=e;
I create an array of alias objects, which I am not sure is what I have to do. What I usually have done is:
this._emps[this._numOfEmps)=new Employee(e);
But since Employee class is abstract I can't do that.
This is a polymorphism practice, so I guess the professor wanted us to put Workers and Managers in the array, but I can't add Workers and Managers to the array in the method.
Any help will be great,
Thank you.
Upvotes: 0
Views: 202
Reputation: 14039
I think it's perfectly OK to create an array of reference objects. There should be no problem with that.
However, if you want to create copies, then check the clone
method, implement it and use it in addEmployee
.
Here is an example of how to implement Cloneable - http://www.jusfortechies.com/java/core-java/cloning.php
Then
this._emps[this._numOfEmps]=e.clone();
++this._numOfEmps;
Upvotes: 1