gpt4 book ai didi

java - 从Java中的另一个类获取数据

转载 作者:行者123 更新时间:2023-12-02 08:07:14 25 4
gpt4 key购买 nike

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

好的..我已经有了项目的类(class)。现在我必须编写 CartItem 类。给出的描述如下:

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

只是想知道这是否正确。

最佳答案

不,这不正确。看看你的构造函数:

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

在这里,您正在调用 getters 并完全忽略调用者传入的值。我认为您不想这样做......想想构造函数需要做什么为了填充新构造的对象...

(您还应该考虑使这些类不可变,但这是一个稍微不同的问题。)

关于java - 从Java中的另一个类获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7966970/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com