Christian Christian - 3 months ago 10
Java Question

interface and object inheritance

I have this following code snippet.

Queue<Node> queue = new LinkedList<Node>();
Node curr = queue.remove();

is a method of LinkedList.
is a method of Queue. Queue is the interface and LinkedList is the object that implements the queue. From what I have learned, when you declare an object as type interface and then assign it to a new object, that object must implement all the methods in the interface and can have other methods that are not specified in the interface. Now,
is a method not specified in the Queue interface, but it is specified in the LinkedList class. However, when I call removeFirst(), I get an error saying "Cannot find symbol." What am I miss understanding? Both the Queue and LinkedList are from Java's util library. I am using this to write a BFS method.


Your variable queue is of type Queue so when you access your object through it, you can only use features that are in the Queue interface. The fact that it's 'really' a LinkedList means that it has the extra methods, but the fact that you're treating it as a Queue means you're effectively promising not to use them.

If you were to create a LinkedList variable and point it at the same object, you'd see the LinkedList methods.

The point of this is that your code that uses this interface doesn't need to change if you change the concrete type of the list later in the life of the project, as long as the new type you use still implements Queue. By acting as though removeFirst doesn't exist, the compiler makes sure you don't shoot yourself in the foot from the perspective of future maintenance by using features not all queues necessarily will have.