为什么我们需要这个问题的接口?

why do we need interface in this question?

在以下来自一本书的代码中,假设 矩形 是具有多个属性的 class。 ComparableRectangle class 的目的是比较两个矩形对象和 return 中较大者的面积,取值1。另外,这个 class 已经实现了一个 可比较的 接口。我的问题是为什么必须实现这个接口。如果我们自己写这个 compareTo 方法而不实现这个接口会怎样?接口的目的不就是使用多态吗?这里我们不想使用多态,为什么要实现接口呢?

public class ComparableRectangle extends Rectangle
implements Comparable<ComparableRectangle> {

public ComparableRectangle(double width, double height) {
super(width, height);
}
    
@Override // Implement the compareTo method defined in Comparable

public int compareTo(ComparableRectangle o) {
 if (getArea() > o.getArea())
 return 1;
 else if (getArea() < o.getArea())
 return −1;
 else
 return 0;
   }
 }

来自official documentation

Lists (and arrays) of objects that implement this interface can be sorted automatically by Collections.sort (and Arrays.sort). Objects that implement this interface can be used as keys in a sorted map or as elements in a sorted set, without the need to specify a comparator.

换句话说,您可以实现自己的比较方法,它可以让您比较两个矩形,但您将无法在其他已排序的集合中使用您的 class 和 classes,需要排序。

您不必这样做,除非您想在相似的对象之间进行自然排序。假设您要对 List<ComparableRectangles> 进行排序。排序方法的签名可能如下所示:

public void <T extends Comparable<? super T>> sort(List<T> list) {
}

如果 T 没有实现 Comparable 接口,您将无法将 T 的列表传递给排序方法,因为该方法无法知道如何对列表进行排序。该方法不能仅仅假设它可以调用 compareTo(它可能不存在,因为它不是 List 接口中定义的方法)。

幸运的是,Collections.sort() 方法允许对未实现 Comparable 接口的对象列表进行排序。要对这样的 List 进行排序,您必须自己提供 Comparator。鉴于以下 class,您可以这样做:

class MyObject {
    int a;
    public MyObject(int a) {
        this.a = a;
    }
    public String toString() {
        return a+"";
    }
    
    public int getA() {
        return a;
    }
}


List<MyObject> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
    list.add(new MyObject((int)(Math.random()*100)));
}
System.out.println(list);
Collections.sort(list, Comparator.comparingInt(MyObject::getA));
System.out.println(list);

打印类似这样的东西。

[90, 75, 10, 78, 9, 14, 79, 43, 49, 47]
[9, 10, 14, 43, 47, 49, 75, 78, 79, 90]

这里是多个 class 实现共同要求的不同示例。

class Lion implements MealTime {
    public void feedMe() {
        System.out.println("\"How about a young gazelle\"");
    }
}

class Koala implements MealTime {
    public void feedMe() {
        System.out.println("\"I want some nice tender eucalyptus.\"");
    }
}

class Gnu implements MealTime {
    public void feedMe() {
        System.out.println("\"Just let me graze please!\"");
    }
}

interface MealTime {
    public void feedMe();
}

public class ZooManagement {
    
    public static void feedem(List<MealTime> list) {
        for (MealTime animal : list) {
            System.out.print("The " + animal.getClass().getSimpleName() + " says -  ");
            animal.feedMe();
        }
    }
    
    public static void main(String[] args) {
        List<MealTime> animals =
                List.of(new Lion(), new Koala(), new Gnu());
        feedem(animals);
    }   
}

版画

The Lion says -  "How about a young gazelle"
The Koala says -  "I want some nice tender eucalyptus."
The Gnu says -  "Just let me graze please!"