0

In one of the tutorials on queues I saw following:

Queue<String> waitingQueue = new LinkedList<>();

Why is this statement valid in Java?

I have seen What does it mean to "program to an interface"? but that does not explain the basic question of why above statement is valid. If Queue is an interface, how can I typecast an object to it? I can only implement Queue interface in a class to provide behavior I need.

What am I missing?

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
  • 3
    "I can only implement Queue interface in a class to provide behavior I need." But `LinkedList` already implements `Queue`. You're just saying "I want my variable to be able to contain a reference to an object of any class that implements `Queue`" - and then assigning it a value which is a reference to a `LinkedList`, because that implements `Queue`. – Jon Skeet Apr 27 '20 at 08:39
  • LinkedList is a class that implements the Queue interface. Why do you feel the above shouldn't be valid? – Stultuske Apr 27 '20 at 08:39
  • 2
    The basic skill to acquire here is to always look up the class you are not familiar with in the Java API documentation. In this case, look up [`LinkedList`](https://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.html). – RealSkeptic Apr 27 '20 at 08:45

1 Answers1

3

What is an interface

An interface is basically a contract saying "these are the methods that any class implementing this interface must implement".

Declaring a variable or field with an interface-type basically says "I don't care what the specific class is that gets assigned here, as longs as it follows the contract."

LinkedList follows the contract set out by Queue by implementing all the required methods.

Therefor we can assign a reference to an object of type LinkedList to a variable of type Queue.

"There can be no instance of an interface"

Developers often learn that "you can't instantiate an interface", which is correct but slightly misleading.

You can have an object that is an instance of an interface type by having an instance of a concrete class that implements that interface.

So while you can't execute new Queue<String>() (since you can't instantiate an interface) the expression new LinkedList<String>() actually returns a Queue<String> (because a LinkedList<String> is-a Queue<String>, in a similar way that it is-a Object).

Community
  • 1
  • 1
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614