2011-07-21 72 views
2

在下面的代码片段,我不看好的为什么我需要施放?

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; 
    } 
} 
+0

你为什么不试试看看会发生什么? – skaffman

回答

4

的想法不存在,你需要告诉对待otherProduct的语言。在你做之前,它只会将其视为Object,它不具有id属性。

1

如果您不将Object obj转换为产品,则无法访问id字段。这就是为什么,前面有一张支票。如果是类型产品比返回false ...

欢呼

1

一个Object对象不具有id场,所以你不能访问这样的领域,这就是为什么你将它转换为Product(也适用 - ((Product)obj).id - 您访问铸造obj的ID)。此外,由于您想覆盖equals方法,因此您必须获取与原始方法相同类别的对象(Object)。

1

那还不如写为:

return this.id == ((Product)other).id;

的对象根本不具有属性“ID”,如果你不类型它转换为产品,因此,你可以不检查ID是相同。因此将对象类型化为Product。

0

这不起作用,因为您正在比较两个产品对象的id属性。