1

Noob Java question:

Could someone explain the difference between

1. Queue<Integer> q = new LinkedList<Integer>() and
2. LinkedList<Integer> q = new LinkedList<Integer>()

in Java? I had assumed that in declaration 1., I wouldn't be able to use LinkedList specific methods and could only use those described by the Queue interface. However, I just tried q.size() and found that that worked, although that is not a part of the Queue interface.

Is the difference in passing these objects as parameters? What is the difference?

Casey Patton
  • 4,021
  • 9
  • 41
  • 54

3 Answers3

3

Queue implements Collection, which has a size() method.

The difference in these two declarations is, as you indicated, a limited amount of methods available and more implementing types allowed for - for example - method parameters.

Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
  • Ah ok. So my initial suspicion is correct, that I only have access to Queue methods and not those specific to LinkedList in example 1? I usually see it done this way in examples. Is the main benefit here polymorphism? So I could have an array of Queues, or pass it into methods as a Queue, etc.? Any other specific reason this is a good practice? – Casey Patton Jul 07 '13 at 00:14
  • If - for example - you have a method that takes a `Queue` as parameter then you will be able to call that method with a `PriorityQueue`, `LinkedList`, etc. It allows for more abstract code and changes to your implementation without breaking the contract of another method. – Jeroen Vannevel Jul 07 '13 at 00:19
  • 3
    You should use the highest (closest to Object) abstraction that makes sense in your particular case. Just be careful to match the abstraction to the semantics you want to have available wherever you use the object. I once made the mistake of abstracting all the way up to `Collection` for an interface design, when the semantics called for `List`, and had to go back and refactor everything. – Jim Garrison Jul 07 '13 at 00:21
1

That's because Queue interface implements Collection interface which has size() method.

luke657
  • 826
  • 2
  • 11
  • 28
0

The difference is that with the first, you are coding to an interface which gives you much more flexibility in the implementation. It may not matter so much in this example, but will matter much more when you create complex programs with many interrelated classes and need to simplify connections and allow for ability to upgrade or enhance one module in isolation of other modules.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373