Java implements a simple supermarket management system (including source code)

Java supermarket management system 1.0 (including source files, will continue to be optimized in the future~)


Preface

I learned java in a scattered time for a month. Through this "supermarket management system" exercise, I hope to give some reference to friends who started learning java together, and hope that the big guys will give more pointers and criticisms~


One, determine the demand

Program overview: The
small supermarket commodity sales management system selects four types of commodities in the small supermarket for management.
The four categories of commodities are: food, cosmetics, daily necessities and beverages (four categories).
Each type of commodity includes the name of the commodity and the profit of the commodity (including the selling price, purchase price, and inventory of the commodity). (Five attributes)
Each category of different commodities also has special information that distinguishes them from other commodities (sub-category-specific attributes). For example, there are wholesalers for food, brands for cosmetics, and manufacturers for beverages.

The above text can determine the following points

  1. The program must realize the four basic functions of " add, delete, modify, and check " + display profit
  2. This program requires operations on four categories of commodities, so the classification is very clear, only four categories need to be created to represent the four categories of commodities.
  3. In this program, products are required to have (the following attributes) product name, product profit , selling price, purchase price, and inventory (of course we can add an additional attribute: product id to achieve a more clear equals comparison, which will be mentioned later) .
  4. In this program, it is required to have its own unique information for different types of goods ( food has wholesalers, cosmetics have brands, and beverages have manufacturers )

Through the above content, we probably have preliminary ideas and ideas for this program, let's analyze in depth which classes and methods are needed

Two, determine the class, interface, method implementation

1. Determine the class

As mentioned above: we need to define four classes to represent the four types of commodities, then can we extract the same characteristics (attributes) from the four classes before writing to introduce the idea of ​​inheritance?

Obviously it is possible. We can define a product category Waresas the parent category, ( and use polymorphism to switch the different references of theWares parent category ). The parent category contains the common features of the four categories of products (with product name, selling price, purchase price, The five attributes of inventory, product number id), and its sub-categories are of course food Food, cosmetics Cosmetic, daily necessities DailyUsingand beverages Drinking, so that the category in the program is determined

We can think more deeply: it Warescan be a normal class or an abstract class. How do we choose?

In fact, both are possible in terms of function implementation, but when ordinary classes implement interfaces, they must rewrite every method in the interface, while abstract classes do not need them; besides, it Waresis the parent class of the four types of goods. When operating on a commodity, you only need to manipulate the object of its subclass. There is no need to instantiate the Waresobject, so we choose to Waresdefine it as an abstract class.

Food: About four subclasses Food, beverages Drinking, cosmetics Cosmetic, daily necessities category DailyUsingdetermined

The four subclasses only need to inherit from the parent class Wares, the common attributes are naturally inherited, and the characteristic attributes can be written separately in each class.

//Wares类中的属性
//商品名字
private String name;
//商品编号
private int id;
//商品进价
private double inPrice;
//商品售价
private double outPrice;
//库存量
private int Count;

Note: WaresWe’d better set the attributes of its subclasses as private attributes, setterand getterthen access through and methods to develop a good habit of encapsulation~

2. Determine the interface

The commodity class Wareswill contain the static characteristics (attributes) and dynamic operations (methods) shared by all commodity classes and their subclasses. The properties can be initialized one by one in the class, but the methods should be included in this class one by one. Write the method body?

We can use the interface to declare all the methods needed by our program into the interface one by one, without implementation, just wait for the parent class Waresto implementinterface, and then let its subclass implement the methods in the interface one by one (overwrite) Can

3. Determine the method

Let's determine the method according to the program requirements (requirements: add, delete, modify, check, display profit)

We can also add the "traverse all products" function, so that we can judge whether the addition, deletion, modification, and checking function can be realized when the program is debugged , which plays a role of verification

Therefore, we have determined the following methods:

public interface Operations {
    
    
    /*
        添加商品信息
     */
    void addWareInfo(ArrayList<Wares> arrayList);
    /*
        输出商品信息
        注意:需要重写toString方法
     */
    void printWareInfo(ArrayList<Wares> arrayList);

    /*
        查询商品信息
        注意:需要重写equals方法
     */
    void findWareInfo(ArrayList<Wares> arrayList);
    /*
        计算并显示某个商品的利润
        注意:需要重写equals方法
     */
    void countWarePrice(ArrayList<Wares> arrayList);
    /*
        删除商品的信息
        注意:需要重写equals方法
     */
    void delWareInfo(ArrayList<Wares> arrayList);
    /*
        修改货物信息
        注意:需要重写equals方法
     */
    void updateWareInfo(ArrayList<Wares> arrayList);
}

Three, analyze another wave before typing the code~

1.Rewrite equals()?

equals()The purpose of rewriting is to compare two different objects when they have the same content, and hope that the equals method determines that the result is true instead of false. At this time, we need to rewriteequals()

Our custom equals()judgment rule for this program is: when the number and name of the object are the same at the same time, the two objects are judged to be the same object
. Obviously, whether this program is the four basic functions of "add, delete, modify, and check" operations, or verify whether the user The function of repeatedly adding the same product requires equals comparison of two objects, so rewriting equals()is necessary.

So does every class need to override the equals method?

Obviously, Waresabstract classes are not needed, because when we compare, we compare whether the objects of its subclasses are the same object, not the parent class object (moreover, the parent class is an abstract class and cannot be instantiated, let alone It can be called equals()) so we can be sure: to rewrite the Foodclass, Drinkingclass, DailyUsingclass, Cosmeticclass equals()to be rewritten

/*
    重写equals方法
    自定义为:当名称相同且商品id相同的时候,视为同一件商品
 */
@Override
public boolean equals(Object o) {
    
    
    if (this == o) return true;
    if (o == null || !(o instanceof Wares)) return false;
    Cosmetic cosmetic = (Cosmetic) o;
    return super.getName().equals(cosmetic.getName()) && super.getId()==cosmetic.getId();
}

2. Rewrite toString?

Because of the need to clearly display product information, every time you need to output information, you System.out.print(“…” + 属性1 + “…” + 属性2);can display every piece of information.

But in view of the many times the program outputs, and the System.out.print()method is called internallytoString() .

Therefore, we can rewrite the (parent class) toString method, so that each output has a set of fixed output format, and the System.out.print(实例化的对象名);formatted output can be completed after it is implemented .

So does every class need to be rewritten toString()?

Obviously, the Waresabstract class is not needed, because when we output information, we want to output the information of the four subclass objects (the parent class Waresis an abstract class, and the object cannot be instantiated, let alone can be called toString()), so we can be sure: To rewrite the Foodclass, the Drinkingclass, the DailyUsingclass, the Cosmeticclass toString()to be rewritten

/*
    重写toString方法
 */
@Override
public String toString() {
    
    
    return "化妆品 {\t " + super.getId() +
            "\t   " + super.getName() +
            "\t\t" + super.getInPrice() + "元" +
            "\t\t" + super.getOutPrice() + "元" +
            "\t\t" + super.getCount() + "件" +
            "\t}";
}

3. Rewrite hashCode()?

Java stipulates: if two objects are the same, then their hashCodevalues ​​must be the same; if two objects are the hashCodesame, the equalscomparison of their objects is not necessarily the same.
Therefore, if the equals method is rewritten, the two instances that are not actually the same object are logically equal, but the hashcode is not equal, which is contradictory.

This kind of contradiction will hashMapcause the inconsistency between the actual operation result and the expected operation result in the equal set.
( Personal understanding: equals()Returning true means that two objects are the same and are compared on the same singly linked list. For nodes on the same singly linked list, their hash values ​​should all be the same, so hashCode()the return value should also be Same ).

As far as this program is concerned, the hashMapunderlying data structure of such a collection is not used to store each object (but it is used arrayList), so whether to rewrite the hashCode method has little effect on this program, but in view of the standardization of the program, the following should be followed in principle:

If the equals method of a class is overridden, then the hashCode method must be overridden. And if the equals method returns true, the value returned by the hashCode method must be the same.

/*
    重写hashCode方法
 */
@Override
public int hashCode() {
    
    
    return Objects.hash(brand);
}

4. Determination of storage structure

Classes, interfaces, methods, attributes, data types, and implementation methods have been determined. Now what form should the instantiated objects be stored together?

One is an array, the other is a collection

Obviously, when we are initializing, we don’t know how many commodities need to be stored and cannot estimate the capacity of the array ; the array can only store elements of a single data type . When operating on it (compared to the set provided in the It is very inconvenient for many operations of the collection, and although the search efficiency of the array is high, the efficiency of the insertion search is very low .

In this program, we select arrayListcollections for object storage.

Note: As far as this program is concerned, I personally feel that it is still used hashMap(inquiries are faster) or hashSet(sorting is more convenient), and both can automatically control the characteristics of no duplication of stored information. This is one of the areas where this program needs improvement

Four, summary and source code

Hope this article can help you who are new to java!
If the description or idea in the article is incorrect or inappropriate, I hope the big guys passing by can correct me a lot!

Finally, attach the source code~

Link: https://pan.baidu.com/s/11zu0-HpybqQL46ITh7JC2A
Extraction code: m4do

Guess you like

Origin blog.csdn.net/weixin_45510412/article/details/115030110