The type of the return method that implements the interface.

I am curious to know what is the best practice / convention of SE for handling the return type of methods that implement the interface. In particular, suppose we implement a simple tree with an interface as such:

public interface ITreeNode {
    public ITreeNode getLeftChild();
    public ITreeNode getRightChild();
    public ITreeNode getParent();
}

And we have a TreeNode class that implements this:

public class TreeNode implements ITreeNode {
    private TreeNode LeftChild, RightChild, Parent;
    @Override
    public ITreeNode getLeftChild() {
        return this.LeftChild;
    }

    @Override
    public ITreeNode getRightChild() {
        return this.RightChild;
    }

    @Override
    public ITreeNode getParent() {
        return this.Parent;
    }
}

My question is: should the return type of the corresponding implemented methods be ITreeNode or TreeNode and why.

Eclipse automatically populates TreeNode methods with the returned ITreeNode type. However, changing it to TreeNode does not cause any errors or warnings even with the @Override flag.

+3
source share
4 answers

Java 5 / , . , ( , , ).

+3

, , , , jdk 1.5. Java Java Generics. http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf

TreeNode TreeNode.

+2

You need to decide what your TreeNode object should do. If its nodes can contain other things besides TreeNodes that implement ITreeNode, then not only the return data types must be ITreeNode, but instance members must also have ITreeNode. Otherwise, if this TreeNodes is completely down, then I don’t understand why you are worried about the interface.

+2
source

For me, the return type must be of the Type.Reason interface type, so you can change the underlying implementation later

1 Example> ITreeNode node = new Tree1();  // First Underlying Implementation     
2 Example> ITreeNode node1 = new Tree2(); // Second Underlying Implementation    

I think, please correct me if I am wrong.

0
source

Source: https://habr.com/ru/post/1790509/


All Articles