简体   繁体   中英

send object of an abstract class to constructor of a concrete class Java

I have an abstract class LinearStructure. Class LinkedList and CircularList implements the abstract functions declared in LinearStructure. I also have Queue, Stack and PriorityQueue.

My constructor for Queue looks like this:

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. 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.

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> 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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