简体   繁体   中英

Why methods returns object of interface type?

I am trying to understand the way, how interface works. After doing some research, I found that interfaces are used to specify what a class must do.

I implemented a method( first() )in outer class which will return element of Position<E> instance, but the main point where I get confused is, first() uses a method getNext() from Node class which returns Node<E> object, so why I am able to return Position<E> object instead of Node<E> and I can even return Node<E> object from first() method.

private static class Node<E> implements Position<E> {// Inner Class
    private E element;
    Node<E> previous;
    Node<E> next;

    Node(E element, Node<E> previous, Node<E> next) {
        this.element = element;
        this.previous = previous;
        this.next = next;
    }

    @Override
    public E getElement() throws IllegalStateException {
        if (next == null)
            throw new IllegalStateException("Position no longer valid");
        return element;
    }

    private Node<E> getNext() {
        return next;
    }

}

Outer class method

@Override
public Position<E> first() {
    return header.getNext();
}

Since Node<E> implements Position<E> , each instance of Node<E> is also an instance of Position<E> (or, to be exact, an instance of a class that implements Position<E> ).

Therefore you can return an instance of Node<E> in a method whose return type is Position<E> .

why I am able to return Position object instead of Node

Because, Node implements Position and that implies Node is a type of Position . So, Position can hold any class instance, who implemented it. In your case, it is Node class, referring to getNext method, which returns Node type object

private Node<E> getNext() {
    return next;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM