将抽象类的对象发送到具体类Java的构造函数

时间:2015-02-19 07:11:44

标签: java inheritance constructor abstract

我有一个抽象类LinearStructure。 Linked LinkedList和CircularList实现了LinearStructure中声明的抽象函数。我还有Queue,Stack和PriorityQueue。

我的Queue构造函数如下所示:

public class Queue<T>
{
  private LinearStructure<T> dataStructure;
  public Queue(LinearStructure<T> c)
  {
        dataStructure =  c;
  }
  .....
}

在我的堆栈复制构造函数中,我想这样做:

public Stack(Stack<T> other)
{
      Queue<T> temp = new Queue<T>(new LinearStructure<T>());
      this.elements = new Queue<T>(new LinearStructure<T>());
      T val;
      ......
}

但我不能,因为LinearStructure是abtract。 所以在我的主要内容中我想做这样的事情:

LinkedList<Integer> ll = new LinkedList<Integer>();
CircularList<Integer> cl = new CircularList<Integer>();
Stack<Integer> s = new Stack<Integer>(ll);
Queue<Integer> q = new Queue<Integer>(cl);

因此换句话说,Stack和Queue可以接收LinkedList或CircularList的对象。

1 个答案:

答案 0 :(得分:0)

如果您希望确保副本中的LinearStructure<T>与原始版本的类型相同,请将此方法添加到LinearStructure<T>

LinearStructure<T> makeEmpty();

每个子类都应该重写此方法以返回其自己的子类的空集合。现在,您可以按如下方式编写复制构造函数的代码:

public Stack(Stack<T> other) {
    Queue<T> temp = new Queue<T>(other.makeEmpty());
    this.elements = new Queue<T>(other.makeEmpty());
    T val;
    ......
}

现在副本和原始版本中的LinearStructure<T>类型将匹配。

你可以更进一步,实现一个复制功能,如下所示:

LinearStructure<T> makeCopy(LinearStructure<? extends T> other);

这样做可以让你将复制与子类的创建结合起来,这可能很重要,因为每个子类可以单独优化它的创建。