为什么不必在Java中覆盖接口Comparator的两种方法 [英] Why is it not necessary to override both methods of interface Comparator in Java

查看:119
本文介绍了为什么不必在Java中覆盖接口Comparator的两种方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道如果我们想要创建该类的对象,就必须实现接口的所有方法。但是为什么没有必要同时实现接口<$ c $的方法 compare() equals() c>比较器在java?

We know that it is necessary to implement all methods of an interface, if we want to make an object of that class. But why is it not necessary to implement both the methods compare() and equals() of interface Comparator in java?

我同意目的已经解决,但即便如此,为什么不强制覆盖等于()如果我们覆盖比较()?

I agree that the purpose is solved but even then why is it not mandatory to override equals() if we override compare()?

推荐答案

由于所有类都隐式扩展 Object Comparator 的每个实现都有一个equals方法,因为每个类都有 Object 有一个。

Since all classes implicitly extend Object every implementation of a Comparator has an equals method, because every Object has one.

如果使用toString()方法定义接口,它将是相同的。

It would be the same if you define an interface with a toString() method.

 public interface ToString {
      public String toString();
 }

 public class SomeClass implements ToString {
     // toString implicitly implemented, because Object defines it
 }

当你看到它所说的实现ToString时,这是真的,不是吗?

When you look at the class it says "implements ToString" and this is true, isn't it?

这篇关于为什么不必在Java中覆盖接口Comparator的两种方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆