setter 方法出现问题并返回 getter

Trouble with setter method and returning getter

我正在尝试创建一个 setter 方法 (setAvailForAssembly) 来设置 assemblestocklevel,但出于某种原因,我的 if 条件似乎没有任何效果。为什么会这样?

主要Class

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

组装部件Class

    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;

        }

    }

部分Class

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


    }

由于您的 main 方法,您只是忘记调用 setAvailForAssembly() 方法,这就是调用 gette 方法的结果为 0 的原因。

此外,getter 和 setters 通常用于访问字段并且不提供任何额外的逻辑。在您的情况下, setter 没有参数的方法将来可能会使某人感到困惑。只需将其命名为 calculateAvailForAssembly 或类似的名称即可。