java语法int compareQuantity=((水果)compareFrit).getQuantity();不明白

java语法int compareQuantity=((水果)compareFrit).getQuantity();不明白,java,Java,我可以在中浏览以下代码,但我不理解 public int compareTo(Fruit compareFruit) { //I don't understand this typecasting int compareQuantity = ((Fruit) compareFruit).getQuantity(); //ascending order return this.quantity - compareQuantity; //descending

我可以在中浏览以下代码,但我不理解

public int compareTo(Fruit compareFruit) {
    //I don't understand this typecasting
    int compareQuantity = ((Fruit) compareFruit).getQuantity(); 
    //ascending order
    return this.quantity - compareQuantity;
    //descending order
    //return compareQuantity - this.quantity;
}
  • 为什么我们要将
    comparefuit
    类型转换为
    Fruit
    类型,而一开始它已经是
    Fruit
    类型了?这似乎是多余的

  • getQuantity
    方法从何而来?我在哪里可以看到这个的源代码


  • 我试图查看一些文档,但找不到任何内容。

    这个cast实际上是多余的,因为mathod compareTo已经将一个水果作为参数,所以不需要它

    至于第二个问题,getQuantity方法来自水果类本身:

    public class Fruit implements Comparable<Fruit>{
    
        // ...
        public int getQuantity() {
            return quantity;
        }
        // ...
    
    }
    
    公共类{
    // ...
    公共整数getQuantity(){
    退货数量;
    }
    // ...
    }
    
    类型转换是多余的,您是对的。
    getQuantity()
    来自水果类的实现。 见:

  • 这种情况下不需要浇铸。语法正确,但强制转换是多余的
  • 它是在水果类中定义的,在compareTo方法上方的几行中
  • 1) 既然葡萄柚已经是一种水果类型了,为什么我们要把它和水果类型进行比较呢?这似乎是多余的

    是的,这是多余的。没有必要进行类型转换。该行可以(必须)更改为:

    int compareQuantity = compareFruit.getQuantity();
    
    2) getQuantity方法从何而来?我在哪里可以看到这个的源代码

    它在上面的
    水果类中定义:

    public class Fruit implements Comparable<Fruit> {
        //...
            public int getQuantity() {
            return quantity;
        }
        //...
    }
    
    公共类{
    //...
    公共整数getQuantity(){
    退货数量;
    }
    //...
    }
    
  • 你是对的,这是多余的
  • getQuantity
    是在
    Fruit
    中声明的方法,或者是在
    Fruit
    扩展的类中声明的方法。它返回一个int

  • 1.不要盲目复制你在互联网上找到的代码。2.在同一页上的
    Fruit
    类中(第4节)。@user3120233如果答案对您有帮助,请不要忘记接受。
    public class Fruit implements Comparable<Fruit> {
        //...
            public int getQuantity() {
            return quantity;
        }
        //...
    }