簡體   English   中英

為什么我需要投?

[英]Why do I need to cast?

在下面的代碼片段中,我不是很清楚

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 在您這樣做之前,它只會將其視為沒有id屬性的Object

如果您不將 Object obj 轉換為 Product,則無法訪問 id 字段。 這就是為什么前面有一張支票。 如果它不是 Product 類型,則返回 false...

干杯

Object object 沒有id字段,因此您無法訪問這樣的字段,這就是您將其轉換為Product的原因(也有效 - ((Product)obj).id - 您訪問轉換后的 obj 的 id) . 此外,由於您要覆蓋equals方法,因此您必須獲得與原始方法相同的 class ( Object ) 的 object 。

也可以寫成:

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

如果您不將 object 類型強制轉換為 Product,則 object 將沒有屬性“id”,因此您無法檢查 id 是否相同。 因此將 object 類型轉換為 Product。

那是行不通的,因為您要比較的是 Products 的兩個對象的 id 屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM