加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 为什么我不能在保留compareTo契约的同时使用新的值组件

发布时间:2020-12-14 05:47:17 所属栏目:Java 来源:网络整理
导读:Joshua Blotch的每个有效 Java: There is no way to extend an instantiable class with a new value component while preserving the compareTo contract,unless you are willing to forgo the benefits of object-oriented abstraction 能否请您通过实例
Joshua Blotch的每个有效 Java:

There is no way to extend an instantiable class with a new value
component while preserving the compareTo contract,unless you are
willing to forgo the benefits of object-oriented abstraction

能否请您通过实例和挑战解释上述问题?你能解释一下Joshua对“价值组件”的意义以及其他类型的组件是否可用.

This frees you to implement whatever compareTo method you like on the
second class,while allowing its client to view an instance of the
second class as an instance of the first class when needed.

你能解释一下约书亚在二等作为第一堂课时的意思吗?

解决方法

Can you please explain the above with examples and the challenges?

当然.考虑这样的两个类 – 我省略了所有的吸气剂,安装者等,但希望你得到漂移:

class NamedThing {
    String name;
}

class Person extends NamedThing {
    Date dateOfBirth;
}

忽略这是否是一个很好的继承示例 – 这是一个简单的例子.

NamedThing按字母顺序实现基于名称的比较是很自然的.

对于人来说,实施比较首先比较名称(因此在这方面保持一致),然后检查一个出生日期早于另一个日期也是很自然的.

现在想象一下:

NamedThing person1 = new Person("Jon",date1);
NamedThing person2 = new Person("Jon",date2);
NamedThing thing = new NamedThing("Jon");

int comparison1 = person1.compareTo(thing);
int comparison2 = person2.compareTo(thing);
int comparison3 = person1.compareTo(person2);
int comparison4 = thing.compareTo(person1);

你想要所有这些结果是什么?如果Person.compareTo足够聪明,只能将其日期处理应用于Person的实例,那么您可能希望comparison1和comparison2为0,但compare3为非零.

推测compare4必须为0,因为它使用NamedThing.compareTo,它只比较名称.

从根本上说,尝试比较不同类型的实例存在问题.它最终变得更清晰,有一个比较的外部定义,它定义了它将使用的比较.因此,你可以有一个Comparator< Person>它只接受Person引用并使用名称和日期,以及Comparator< NamedThing>只按名称比较.行为将具有对称性和清晰度.

Can you also explain what Joshua means by second class as an instance of the first class?

你已经脱离了背景.它是:“将第二类的实例视为第一类的实例” – 例如

// First class = Animal
// Second class = Zebra
Animal person = new Zebra();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读