gpt4 book ai didi

java - 为什么我不能在保留 compareTo 契约的同时使用新值组件扩展可实例化类?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:59:30 25 4
gpt4 key购买 nike

根据 Joshua Blotch 的 Effective 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 所说的“值(value)组件”是什么意思,还有哪些其他类型的组件可用。

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.

您能否也解释一下 Joshua 所说的 second class as an instance of the first class 是什么意思?

最佳答案

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

当然。考虑像这样的两个类——我省略了所有的 getter、setter 等,但希望你能理解:

class NamedThing {
String name;
}

class Person extends NamedThing {
Date dateOfBirth;
}

忽略这是否是一个好的继承示例 - 这是一个简单的继承示例。

NamedThing 很自然实现基于名称的比较,按字母顺序排列。

Person 也很自然实现比较,首先比较姓名(因此在这方面保持一致),然后检查一个出生日期是否早于另一个。

现在想象一下:

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 的实例,那么你可能会期待 comparison1comparison2为 0,但 comparison3为非零。

大概是comparison4 必须为 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();

关于java - 为什么我不能在保留 compareTo 契约的同时使用新值组件扩展可实例化类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13509286/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com