在下面的代码片段中,我不是很清楚
的用处Product other = (Product)obj;
在我看来,这是多余的。我们可以只删除这个,然后将“return this.id==other.id”更改为“return this.id == obj.id”吗?
public class Product{
String description;
double price;
int id;
public Product(String d, double p, int i){
description = d;
price = p;
id = i;
}
public boolean equals(Object obj){
if(!(obj instanceof Product){
return false;
}
Product other = (Product)obj;
return this.id == other.id;
}
public int hashcode(){
return id;
}
public String toString(){
return id + " "+description;
}
}
最佳答案
这里的想法是您需要告诉语言将other
视为Product
。在您这样做之前,它只会将其视为一个 Object
,它没有 id
属性。
关于java - 为什么我需要施法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6782727/