返回子类型对象而不是接口所要求的超类型对象 [英] Returning a subclass type object instead of superclass type object as demanded by interface

查看:178
本文介绍了返回子类型对象而不是接口所要求的超类型对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为Node的类和另一个名为ClassicNode的类,它扩展了Node。现在我有一个由ClassicNode类实现的接口AgentInterface。接口声明必须有方法

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();

如您所见,返回类型应为Node类型。但是在类ClassicNode中我可以像这样实现它: -

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
}

这会满足界面吗? (因为ClassicNode继承了Node)

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

推荐答案

是的;它被称为协变返回。但是请注意,你不能用参数做同样的事情;它们必须完全匹配。

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

这篇关于返回子类型对象而不是接口所要求的超类型对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆