栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

接口如何包含在其签名或返回类型中引用接口的具体实现类型的方法?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

接口如何包含在其签名或返回类型中引用接口的具体实现类型的方法?

这是

Comparable
接口所面临的确切情况(其
compareTo
方法希望采用与调用它的对象相同类型的参数)。那怎么办呢?简称为
Comparable<T>
。这个想法是,一个实现类“应该”
Comparable
以自身作为参数来实现(允许它与自身“比较”)。但这不是强制性的(因为没有办法这样做)。

是的,正如你指出,这将允许任何类来实现

Comparable
与任何其他类的参数:
class Foo implementsComparable<Bar>
其中,
Foo
Bar
没有关系对方。但是,这并不是真正的问题。

所有需要

Comparable
对象的方法和类(排序,最大值等)都具有以下通用类型约束
<T extends Comparable<? superT>>
。这样可以确保类型T的对象与其自身具有可比性。这样,它是完全类型安全的。因此,强制执行不是在Comparable接口的声明中进行的,而是在使用它的地方进行的。

(I notice that you use

<T extends MyInterface<T>>
while
Comparable
uses
simply
<T>
. Although
<T extends MyInterface<T>>
will exclude cases where
the type parameter does not implement
MyInterface
, it will not exclude cases
where the type parameter does implement
MyInterface
, but is different than
the class. So what’s the point of half-excluding some cases? If you adopt
Comparable
‘s way of restricting it where they are used, it’s type-safe
anyway, so there is no point in adding more restrictions.)



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/410284.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号