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()
来自水果类的实现。
见:
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;
}
//...
}