我对某些事情有点困惑,如果你们都能对此有所了解,我将不胜感激。我有一个类支付,它有一些方法和 getter/setter。例如,我是使用 ItemCost 方法返回属性 itemCost 的阀门还是使用 getter?
public class Payment {
private int itemCost, totalCost;
public int itemCost(int itemQuantity, int itemPrice){
itemCost = itemPrice * itemQuantity;
return itemCost;
}
public int totalCost(BigDecimal itemPrice){
totalCost = totalCost + itemCost;
return totalCost;
}
public int getBalance(int clickValue, int totalCost){
totalCost = totalCost - clickValue;
return totalCost;
}
public int getTotalcost(){
return this.totalCost;
}
public void setTotalcost(int totalCost){
this.totalCost = totalCost;
}
public int getItemcost(){
return this.itemCost;
}
public void setItemcost(int itemCost){
this.itemCost = itemCost;
}
}
好的,而不是实例化: int cost = payment.itemCost(quantity, itemPrice) 在另一个类中
做:payment.itemCost(quantity, itemPrice) payment.getItemcost
?
编辑 2:让所有方法都返回 void 并且只使用 getter 是更好的编码吗?
public class Payment {
private int itemCost, totalCost;
public void calculateItemcost(int itemQuantity, int itemPrice){
itemCost = itemPrice * itemQuantity;
}
public void calculateTotalCost(BigDecimal itemPrice){
this.totalCost = totalCost + itemCost;
}
public void calculateBalance(int clickValue, int totalCost){
this.totalCost = totalCost - clickValue;
}
public int getTotalcost(){
return this.totalCost;
}
public void setTotalcost(int totalCost){
this.totalCost = totalCost;
}
public int getItemcost(){
return this.itemCost;
}
public void setItemcost(int itemCost){
this.itemCost = itemCost;
}
}