Returning a subclass type object instead of superclass type object as demanded by interface

北慕城南 提交于 2019-12-25 03:53:36

问题


I have a class called Node and another class called ClassicNode which extends Node. Now I have an interface AgentInterface implemented by ClassicNode class. The interface states that there must be a method

Node selection();

As you can see, the return type should be of type Node. But in the class ClassicNode can I implement it like this instead:-

ClassicNode selection(){
    //Code
}

Will this satisfy the interface? (since ClassicNode inherits Node)


回答1:


Yes; it's called covariant return. Note, though, that you cannot do the same thing with parameters; they must match exactly.




回答2:


So,why don't you do a experiment? less work to do. you can just add annotation @Override upon the signature of your Method, then try to compile the code, if successfull, means that works, or failure.



来源:https://stackoverflow.com/questions/6475312/returning-a-subclass-type-object-instead-of-superclass-type-object-as-demanded-b

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!