开发者

Return type of method that implements an interface

开发者 https://www.devze.com 2023-02-09 06:00 出处:网络
I am curious to know what is the best practice / SE convention of handling return type of methods that implements an interface. Specifically, assume we are implementing a simple tree, with interface a

I am curious to know what is the best practice / SE convention of handling return type of methods that implements an interface. Specifically, assume we are implementing a simple tree, with interface as such:

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

And we have a class TreeNode that implements that:

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 respective implemented methods be ITreeNode or TreeNode, and why.

Eclipse automatically populate the methods for TreeNode with return type of ITreeNode. However c开发者_StackOverflow中文版hanging it to TreeNode doesn't cause any errors or warnings even with the @Override flag.


Since Java 5, the overridden methods can return any subclass of the interface/class of the return type mentioned in super class. I will stick to returning the interface unless specifically required (this happens mainly while refactoring the old code where the client was already using a specific implementation class while we are now refactoring it to form a class hierarchy).


Well, what you have mentioned has called as covariant return, it did not exists prior to jdk 1.5. Covariant return concepts has been added to Java language to support Java Generics. For more information , http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf

I would prefer TreeNode as return type at TreeNode class.


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 types need to be ITreeNode, but the instance members also need to be ITreeNode. Otherwise if it's TreeNodes all the way down then it's not clear to me why you're bothering with an interface.


According to me,The return type should be that of Interface Type.Reason so that 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 im wrong.

0

精彩评论

暂无评论...
验证码 换一张
取 消