user2913464
user2913464

Reputation: 13

cast priorityQueue to my customized interface

public class testCast {

    public interface dataQueue extends Queue<Object>{};

    public static void main (String test[]){        
        dataQueue queue = (dataQueue) new java.util.PriorityQueue<Object>();
        queue.add("Test");
        System.out.println(queue.peek());
    }
}

I am wondering why this would cause a casting error.... it would work if I do

Queue queue = (Queue) new java.util.PriorityQueue<Object>(); Does anyone know why?? Thanks in advance

Upvotes: 0

Views: 64

Answers (1)

Henry Keiter
Henry Keiter

Reputation: 17188

Put simply, because a PriorityQueue is a Queue, but not a DataQueue. The actual class definition matters in Java: just because two interfaces are identical doesn't mean you can cast any implementation of one to the other.

  • DataQueue is an interface that extends the Queue interface.
  • PriorityQueue is a class that implements the Queue interface.
    • It does not implement the DataQueue interface.
  • Therefore, a PriorityQueue cannot be cast to DataQueue.

The hierarchy might make it clearer: just because they have a common ancestor doesn't mean you can cast one to the other.

            Queue
      ________|________
     |                 |
 DataQueue       PriorityQueue

To be even more pedantic about it, let's ramp up the clarity, since the relationship between Queue and DataQueue is different from the relationship between Queue and PriorityQueue. The following MSPaint diagram uses solid lines for inheritance, and dashed lines for interface-implementation.

DataQueue inherits; PriorityQueue implements.

So, you can't get from a PriorityQueue directly to a DataQueue. If you did really want to be able to make a PriorityQueue and call it a DataQueue for some reason, this is what you could do: extend PriorityQueue with a new class, and implement your DataQueue interface.

public class MyQueue extends PriorityQueue<Object> implements DataQueue {
    // Anything you want goes here, or just leave it empty if you only want the default constructor.
}

MyQueue inherits from PriorityQueue, and implements DataQueue

Then you can write DataQueue q = new MyQueue(); to your heart's content.


Finally, note that this wouldn't work if you tried to inherit from two different classes. Java does not support multiple inheritance. This hierarchy is only possible because DataQueue is an interface, rather than a class.

Upvotes: 5

Related Questions