[英]send object of an abstract class to constructor of a concrete class Java
I have an abstract class LinearStructure. 我有一个抽象类LinearStructure。 Class LinkedList and CircularList implements the abstract functions declared in LinearStructure. Linked LinkedList和CircularList实现了LinearStructure中声明的抽象函数。 I also have Queue, Stack and PriorityQueue. 我还有Queue,Stack和PriorityQueue。
My constructor for Queue looks like this: 我的Queue构造函数如下所示:
public class Queue<T>
{
private LinearStructure<T> dataStructure;
public Queue(LinearStructure<T> c)
{
dataStructure = c;
}
.....
}
And in my copy constructor for stack I want to do this: 在我的堆栈复制构造函数中,我想这样做:
public Stack(Stack<T> other)
{
Queue<T> temp = new Queue<T>(new LinearStructure<T>());
this.elements = new Queue<T>(new LinearStructure<T>());
T val;
......
}
But I can't because LinearStructure is abtract. 但我不能因为LinearStructure是abtract。 So in my main I want to do something like this: 所以在我的主要内容我想做这样的事情:
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);
So in other words Stack and Queue can receive either an object of LinkedList or CircularList. 换句话说,Stack和Queue可以接收LinkedList或CircularList的对象。
If you wish to make sure that the LinearStructure<T>
in the copy is of the same type as in the original, add this method to LinearStructure<T>
: 如果要确保副本中的LinearStructure<T>
与原始类型中的LinearStructure<T>
相同,请将此方法添加到LinearStructure<T>
:
LinearStructure<T> makeEmpty();
Each subclass should override this method to return an empty collection of its own subclass. 每个子类都应该重写此方法以返回其自己的子类的空集合。 Now you can code your copy constructor as follows: 现在您可以按如下方式编写复制构造函数的代码:
public Stack(Stack<T> other) {
Queue<T> temp = new Queue<T>(other.makeEmpty());
this.elements = new Queue<T>(other.makeEmpty());
T val;
......
}
Now the type of LinearStructure<T>
in the copy and in the original would match. 现在副本和原始中的LinearStructure<T>
的类型将匹配。
You could go further and implement a copy function instead, like this: 您可以更进一步实现复制功能,如下所示:
LinearStructure<T> makeCopy(LinearStructure<? extends T> other);
Doing so would let you combine copying with creation of subclass, which may be important, because each subclass could optimize its creation separately. 这样做可以让您将复制与子类的创建结合起来,这可能很重要,因为每个子类可以单独优化其创建。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.