In the following code snippet, I am not very clear about the usefulness of
Product other = (Product)obj;
It seems to me that it is redundant. Can we just remove this one, and change “return this.id==other.id” to “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;
}
}
The idea there is that you need to tell the language to treat
otheras aProduct. Until you do, it only sees it as anObject, which doesn’t have anidattribute.