I'm going over the implementation of positional lists and I am confused on why we are able to pass in an "instance" of an interface to a certain functions inside a class that implements it.
For the interface Position :
public interface Position <E>{
public Object getElement ();
}
And a Node Class that implements this interface
private static class Node<E> implements Position<E> {
private E element; // reference to the element stored at this node
private Node<E> prev; // reference to the previous node in the list
private Node<E> next; // reference to the subsequent node in the list
public Node(E e, Node<E> p, Node<E> n) { element = e; prev = p;next = n;}
//other functions
}
If we were to use the Node Class in a seperate class, I saw functions that seem to pass in an instance of a Postion interface to the function. For example, a function might look like:
private Node<E> validate(Position<E> p) throws IllegalArgumentException {
if (!(p instanceof Node)) throw new IllegalArgumentException("Invalid p");
Node<E> node = (Node<E>) p; // safe cast
if (node.getNext( ) == null) // convention for defunct node
throw new IllegalArgumentException("p is no longer in the list");
return node;
}
Another example
public Position<E> before(Position<E> p) throws IllegalArgumentException {
Node<E> node = validate(p);
return position(node.getPrev( ));
}
I'm not sure what is actually happening when we are passing in an instance of an interface into a function. If we called the function and passed in a Node variable, how is that related specifically to an interface? As stated above, this is an excerpt from my textbook on Positional List and I can't seem to understand how this abstraction works.
EDIT:
In this function, we set the parameter as a node instead of the interface. If a Node implements Position anyways, what is the point of returning a Position from the function?
/** Returns the given node as a Position (or null, if it is a sentinel). */
private Position<E> position(Node<E> node) {
if (node == header || node == trailer)
return null; // do not expose user to the sentinels
return node;
}