2015-10-16 70 views
0

我試圖做一個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; 
     } 


    } 

setter not working!

+1

你還沒有顯示任何代碼調用你的'setAvailForAssembly'方法。請注意,對於setter沒有參數也是很奇怪的......因爲你不需要任何新的狀態,所以我可能只是把這個邏輯放到getter中。 –

+0

如何將邏輯添加到getter方法中?因爲它只需要一個返回語句並添加條件導致錯誤 – danielb

回答

1

由於您的主要方法,您只需忘記調用setAvailForAssembly()方法,這就是您通過調用gette方法得到0的原因。此外,getters和setter通常用於訪問字段,並且不提供任何其他邏輯。在你的情況下,沒有爭論的二傳手法,可能會在將來混淆某人。把它叫做calculateAvailForAssembly或者類似的東西。

+0

是的,我想我明白了。我創建了一個名爲calulateAvailForAssembly()的方法。在if-else條件中添加並返回裝配體級別; 然後,只需通過此方法作爲getAvailForAssembly()的返回值; – danielb