Enum constructors and methods

Food ordering app

Let’s review what we’ve covered so far, by building a food ordering app.

Before we start, decompose this specification:

You are developing a food ordering app. You need to track which food has been ordered, and the status of the order. The status of each order can be: PLACED, READY, ENROUTE, DELIVERED

Draw a UML class diagram with the classes you need. You can have an abstract food class, with different types of food extending the food super class.

Quiz 5

current time

Food ordering app

Use of enum:

public enum OrderStatus { 
        PLACED,
        READY,
        ENROUTE,
        DELIVERED 
    }

Constructors and methods in enum

The type enum is actually a class.

For each option we can have arguments. Create a constructor (private by default) and a getter.

public enum OrderStatus { 
        PLACED (1),
        READY (2),
        ENROUTE (3),
        DELIVERED (4);
        
        private int sequence;
        
        OrderStatus(int sequence) {
            this.sequence = sequence;
        }
        
        public int getSequence() {
            return sequence;
        }
    }

Using enum methods

I wrote a setStatus(OrderStatus) method in my FoodOrder class to make sure the status setting makes sense

public void setStatus(OrderStatus status) {
        if (this.status.getSequence() < status.getSequence()) 
            this.status = status;
    }

This method could return a boolean to flag if the change in status was successful

More methods in enum

We can set default methods like isReady() that returns false unless we overwrite the method in one of the options

public enum OrderStatus { 
        PLACED (1),
        READY (2) {
            public boolean isReady() {
                return true;
            }
        },
        ENROUTE (3),
        DELIVERED (4);
        
        int sequence;
        
        OrderStatus(int sequence) {
            this.sequence = sequence;
        }
        
        public int getSequence() {
            return sequence;
        }
        
        public boolean isReady() {
            return false;
        }

        }
    } // enum OrderStatus

Complete your app

What other classes and methods should you write to make this a complete application

We will build a GUI on top of this implementation in class