2011-11-01 123 views
0
public class Item { 

    /** 
    * Instance variables for this class 
    */ 

    private String itemName; 
    private int itemQuantity; 

    /** 
    * Contructor for this class 
    */ 

    public Item (String itemName, int itemQuantity) { 
     this.itemName = itemName; 
     this.itemQuantity = itemQuantity; 
    } 
    //setter and getter methods 
    public String getItemName() { 
     return itemName; 
    } 
    public void setItemName(String itemName) { 
     this.itemName = itemName; 
    } 

    public int getItemQuantity() { 
     return itemQuantity; 
    } 
    public void setItemQuantity(int itemQuantity) { 
     this.itemQuantity = itemQuantity; 
    } 
} 

好吧,我已經有了類的項目。現在我必須編寫CartItem類。是給出的描述如下:從Java中的另一個類獲取數據

class CartItem{ 
/* 
Objects of this class are used to hold items that the shopper purchases in the super market. 
There are two attributes in this class, an item (an object created from the Item class) and a quantity (the number of that item that the shopper purchases). You have to write these two attributes. Note that one of the two will have a user defined data type. 
*/ 

} 

public class CartItem { 
    private Item item; //item from the item class 
    private int itemQuantity; //quantity how much shopper buys 

    public CartItem(Item itemName, int itemQuantity) { 
     this.getItem(); 
     this.getQuantity(); 
    } 


    public Item getItem() { 
     return item; 
    } 
    public void setItem(Item item) { 
     this.item = item; 
    } 

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

只是想知道,如果它是正確的,但。

+1

是否有隱藏在某處的實際問題?請幫我發現它。 –

+0

如果你問我,高層次的設計似乎是關閉的。爲什麼你在'Item'類和'CartItem'類中都有數量?您應該將數量保留在CartItem類中,並且只關注「Item」類的單個產品的屬性,例如價格,描述等。 – ladaghini

+0

yeahh,我想了解它背後的潛在原因基於講師的設計,它已經被設計出來了,所有的規格都已經給了我們,我們必須嚴格遵守。 – yoshifish

回答

2

不,這是不正確的。看看你的構造:

public CartItem(Item itemName, int itemQuantity) { 
    this.getItem(); 
    this.getQuantity(); 
} 

在這裏,我們調用干將和完全無視呼叫者已通過價值觀,我不認爲你想這樣做......想想構造什麼。需要以填充新構造的對象做...

(你也應該考慮使這些類不可變的,但是這是一個稍微不同的事情。)

0

一些事情。

1人,可店不止一個Item所以有Item
2構造的List是不正確的,這應該是

public CartItem(Item itemName, int itemQuantity) { 
     this.item = itemName; 
     this.itemQuantity = itemQuantity; 

    } 
+0

該列表應該在購物車對象中,並且它將是一個列表。 –

0

不,這不是。

CartItem的構造函數只需調用this.getItem()this.getQuantity()。這隻會調用方法,顯然會返回null,因爲屬性從不初始化。它應該是:

public CartItem(Item itemName, int itemQuantity) { 
    this.item = itemName; 
    this.itemQuantity = itemQUantity; 
} 

另一個問題是您爲所有字段添加getters和setter,甚至不知道這些方法是否必要。嘗試支持不變性,並且只在絕對必要時提供引導者。我不會解釋所有不可變性的優點,因爲根據你已經知道的,這太早了。但是一個好的經驗法則是:如果不使用方法,不要將方法添加到類中。