gpt4 book ai didi

java - 为什么一个对象应该有一个返回 "this"的方法?

转载 作者:行者123 更新时间:2023-11-29 06:54:45 25 4
gpt4 key购买 nike

我最近在 Java JodaTime 库中偶然发现了一个奇怪的细节。

有一个 Instant 类,它有一个名为 toInstant() 的方法。该方法仅返回 this

/**
* Get this object as an Instant by returning <code>this</code>.
*
* @return <code>this</code>
*/
public Instant toInstant() {
return this;
}

我完全不知道这应该有什么帮助。如果你想调用这个方法,你已经需要你希望从中得到的对象。或者这仅仅是为了满足接口(interface)?

最佳答案

Instant 扩展了实现 ReadableInstantAbstractInstant

DateTime 和其他时间对象也是 ReadableInstant,所以是的,这是满足一个接口(interface);而且,在这种情况下,您正在查看的部分可能没有多大意义。查看 ReadableInstant 的其他实现,它更有意义。

例如

MutableDateTime dateTime = new MutableDateTime();
// Available because MutableDateTime is a ReadableInstant
Instant instant = dateTime.toInstant();

关于java - 为什么一个对象应该有一个返回 "this"的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36742475/

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