[英]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.