2017-05-19 80 views
-2

我有java類適配器,這是錯誤的(Groceries b:getData()),因爲對象無法轉換爲Groceries.java,如果我改爲(Object b:的getData())我不能從Groceries.java調用一個方法b.getProduct()getSn()錯誤:不兼容的類型對象不能轉換爲(java類)

DataAdapter.java

public Groceries getBelBySN(String sn) { 
    Groceries pp = null; 
    for (Groceries b : getData()) { 
     if (b.getProduct().getSn().equals(sn)) { 
      pp = b; 
      break; 
     } 
    } 
    return pp; 
} 

public void updateTotal() { 
    long jumlah = 0; 
    for (Groceries b : getData()) { 
     jumlah = jumlah + (b.getProduct().getHarga() * b.getQuantity()); 
    } 
    total = jumlah; 
} 

這是Groceries.java,我請適配器。

public class Groceries { 
protected Product product; 
protected int quantity; 

public Groceries(Product product, int quantity) { 
    this.product = product; 
    this.quantity = quantity; 
} 

public void setProduct(Product product) { 
    this.product = product; 
} 

public Product getProduct() { 
    return product; 
} 

public void setQuantity(int quantity) { 
    this.quantity = quantity; 
} 

public int getQuantity() { 
    return quantity; 
} 
+2

getData()返回什麼?你能告訴我們'getData()'的代碼嗎? –

+0

getData()是從列表 – Rizal

回答

0

看起來好像getData()不會返回一個Groceries對象。你能提供它的實施嗎? Java中的每個對象都從Object.class繼承,這就是爲什麼您可以毫無問題地投射到它的原因。 Object.class沒有任何你的Groceries函數,這就是爲什麼你調用它們時出錯。您應該首先閱讀一本關於Java中的OOP和OOP的好書。

編輯:

我不知道你的getData()功能的模樣,但它應該是這樣的,使先進的循環工作:

ArrayList<Groceries> myGroceries = new ArrayList<Groceries>(); 

public ArrayList<Groceries> getData(){ 
    return myGroceries; 
} 

那麼你的循環應該運行得很好。

for (Groceries b : getData()) { 
    // Do stuff 
} 
+0

謝謝你現在工作,我添加到適配器 – Rizal

相關問題