我試圖做一個setter方法(setAvailForAssembly),它設置裝配體的等級,但由於某種原因,如果條件似乎沒有產生任何效果。爲什麼發生這種情況?Setter方法和返回吸氣劑的問題
主類
public class TestAssembledPart {
public static void main(String args[]) {
// Constructing two Part objects (the base parts)
Part part0 = new Part("p101", "Crank", 218, 12.20);
Part part1 = new Part("p102", "Pedal", 320, 14.30);
// Constructing AssembledPart object assembled from p101 & p102
AssembledPart part2 = new AssembledPart("p183", "Crank & Pedal", 80, 3.50, part0, part1);
// replenishing stock by 100 items
part2.replenish(100);
System.out.println(part2);
// Supplying the maximum possible assembled parts - combination
// of existing parts and base parts available for assembly
System.out.println("Supplying max number of (assembled) part");
int totalAvail = part2.getStockLevel() + part2.getAvailForAssembly();
System.out.println("part2 stocklevel: " + part2.getStockLevel() + " part2 available for assembly: " + part2.getAvailForAssembly());
}
}
AssembledPart類
public class AssembledPart extends Part {
private Part basica;
private Part basicb;
private int assembledstocklevel;
public AssembledPart(String id, String name, int stocklevel, double unitprice,
Part part0, Part part1) {
super(id, name, stocklevel, unitprice);
this.basica = part0;
this.basicb = part1;
}
public void setAvailForAssembly() {
if(basica.getStockLevel() >= basicb.getStockLevel()){
assembledstocklevel = basica.getStockLevel();
} else assembledstocklevel = basicb.getStockLevel();
}
public int getAvailForAssembly() {
return assembledstocklevel;
}
}
零件類
public class Part {
protected int stocklevel;
public Part(String id, String name, int stocklevel, double unitprice) {
this.id = id;
this.name = name;
this.stocklevel = stocklevel;
this.unitprice = unitprice;
}
public int getStockLevel() {
return stocklevel - qty;
}
public void setStockLevel(int stocklevel) {
this.stocklevel = stocklevel;
}
}
你還沒有顯示任何代碼調用你的'setAvailForAssembly'方法。請注意,對於setter沒有參數也是很奇怪的......因爲你不需要任何新的狀態,所以我可能只是把這個邏輯放到getter中。 –
如何將邏輯添加到getter方法中?因爲它只需要一個返回語句並添加條件導致錯誤 – danielb