繁体   English   中英

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

[英]send object of an abstract class to constructor of a concrete class Java

我有一个抽象类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的对象。

如果要确保副本中的LinearStructure<T>与原始类型中的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);

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

暂无
暂无

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

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