且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

接口中的toString(),equals()和hashCode()

更新时间:2023-09-29 17:02:28

Java中的所有对象都继承自 java.lang.Object 对象提供了那些的默认实现方法。

All objects in Java inherit from java.lang.Object and Object provides default implementations of those methods.

如果你的接口包含其他方法,如果你没有通过提供这些方法的实现来完全实现接口,Java会抱怨。但是在 equals()的情况下, hashCode() toString()(以及你未提及的其他几个)实施已经存在。

If your interface contains other methods, Java will complain if you don't implement the interface fully by providing an implementation of those methods. But in the case of equals(), hashCode() and toString() (as well as a few others that you didn't mention) the implementation already exists.

你可以通过一种方式完成你想要的任务通过在界面中提供不同的方法,比如 toPrettyString()或类似的东西。然后你可以调用那个方法而不是默认的 toString()方法。

One way you might be able to accomplish what you want is by providing a different method in the interface, say, toPrettyString() or something like that. Then you can call that method instead of the default toString() method.