【问题标题】:send object of an abstract class to constructor of a concrete class Java将抽象类的对象发送到具体类 Java 的构造函数
【发布时间】:2015-02-19 07:11:43
【问题描述】:

我有一个抽象类 LinearStructure。 LinkedList 和 CircularList 类实现了 LinearStructure 中声明的抽象函数。我也有队列、堆栈和优先队列。

我的 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 是抽象的。 所以我主要想做这样的事情:

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 的对象。

【问题讨论】:

  • 问题是什么?

标签: java inheritance constructor abstract


【解决方案1】:

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

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&lt;T&gt; 的类型在副本和原件中将匹配。

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

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

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

【讨论】:

    猜你喜欢
    • 2015-03-20
    • 2014-12-15
    • 2018-06-10
    • 1970-01-01
    • 2013-08-29
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 2019-05-12
    相关资源
    最近更新 更多