简体   繁体   English

多态和抽象父类

[英]Polymorphism and abstract parent class

In the practice I am doing now I have 3 classes in the hierarchy: Employee (abstract class) Worker extends Employee Manager extends Employee 在实践中,我现在在层次结构中有3个类: Employee (抽象类) Worker扩展Employee Manager扩展Employee

I have an additional class who uses those 3 classes: Factory . 我还有一个使用这3个类的类: Factory

I have to build now a method which adds an Employee e to an array of Employees. 我现在必须构建一个将Employee e添加到Employees数组的方法。 Attributes: 属性:

_emps - an array of type Employee . _emps- Employee类型的数组。 _numOfEmpes - indicates the number of employess in the array. _numOfEmpes-表示数组中的受雇人数。

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. 但是由于Employee类是抽象的,所以我不能这样做。

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. 这是一种多态实践,所以我想教授希望我们将Workers和Managers放入数组中,但是我无法在该方法中将Workers和Managers添加到数组中。

Any help will be great, 任何帮助都会很棒,

Thank you. 谢谢。

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 . 但是,如果要创建副本,请检查clone方法,实现它并在addEmployee使用它。

Here is an example of how to implement Cloneable - http://www.jusfortechies.com/java/core-java/cloning.php 下面是如何实现Cloneable的一个例子- http://www.jusfortechies.com/java/core-java/cloning.php

Then 然后

this._emps[this._numOfEmps]=e.clone();
++this._numOfEmps;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM