库存跟踪器中方法的问题

时间:2015-10-26 04:34:34

标签: java

这是我关于堆栈交换的第一篇文章,所以我不确定你需要什么,但这是我的问题:

我正在为我的java类创建一个库存跟踪器,我遇到了一个无法使用方法addItem(Item newItem)的问题,因为类Inventory不是静态的,也没有构造函数。我们有一个UML图 uml diagram

我们应该工作,它不包括Inventory的构造函数,并且没有提到静态。

我不确定你还需要什么,但是非常感谢任何帮助!

谢谢!

public class InventoryTrackerInterface {

    public Inventory inv;

    public static void main(String[] args) {
        //test item
        Item b1 = new Item("abc",1,123,"01345");
    }
}

public class Inventory {

    private Item[] itemArray;
    private int totalItems = 0;

    public int getTotalNumberOfItems() {
        return totalItems;
    }

    public Item getItem(int index) {
        if (index < 0 || index >= totalItems) {
            return null;
        } else {
            return itemArray[index];
        }
    }

    public void addItem(Item newItem) {
        if (newItem == null) {
            System.out.println("Item not added.");
        } else {
            itemArray[totalItems] = newItem;
            totalItems++;
        }
    }

    public void saveInventoryToFile(String fileName) {
    }

    public void loadInventoryFromFile(String fileName) {
    }
} 

public class Item {

   private String name;
   private int quantity;
   private double price;
   private String upc;

   private Item() {



   }


   public Item(String name, int qty, double price, String upc) {



   }


   public String getName() {

      return name;

   }


   public int getQuantity() {

      return quantity;

   }

   public double getPrice() {

      return price;

   }

   public String getUPC() {

      return upc;

   }
}

1 个答案:

答案 0 :(得分:1)

您无需显式定义构造函数即可实例化类。在这种情况下,会自动创建默认构造函数。 UML图通常只会在需要带有参数的情况下指示构造函数,如Item的情况。

您可以将inv属性定义为static:

public class InventoryTrackerInterface
{
    public static Inventory inv;

    public static void main(String args[])
    {
         // Test items
         Item b2 = new Item("abc",1,123,"01345");
         Item c2 = new Item("dfe",2,456,"56789");

         // Inventory object
         inv = new Inventory();

         inv.addItem(b2);
         inv.addItem(c2);

     }
}

或通过InventoryTrackerInterface实例访问它:

public class InventoryTrackerInterface
{
    public Inventory inv;

    public static void main(String args[])
    {
         // Test items
         Item b2 = new Item("abc",1,123,"01345");
         Item c2 = new Item("dfe",2,456,"56789");

         InventoryTrackerInterface instance = new InventoryTrackerInterface();

         // Inventory object
         instance.inv = new Inventory();

         instance.inv.addItem(b2);
         instance.inv.addItem(c2);

     }
}