Suhas Srivastava
Suhas Srivastava

Reputation: 33

Returning subclass in an interface method

I wanna make a linked list project in which I have created an interface and a class

CLASS:

  public class MainNode<T> implements Node<T>
    {
        public T data;
        public MainNode<T> next;
        public MainNode<T> nextIs()
        {
            return next;
        }
    }.           //all other methods are defined and work fine

INTERFACE:

public interface Node<T>
{
    public SUB_CLASS_RETURN_TYPE nextIs();
}         //all other methods are declared as needed

Problem: the problem is that what should be written in SUB_CLASS_RETURN_TYPE to return the object or reference of derived/sub class

Upvotes: 2

Views: 1873

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533492

What you can do is use generics

public interface Node<N extends Node<N>> {
    public N nextLs();
}

public class MainNode implements Node<MainNode> {
    @Override
    public MainNode nextls() {
        ...
    }
}

Upvotes: 4

Related Questions