Java Program to show usage of Enum which prints the size of coffee mug
Program
class Coffee
{
enum CoffeeSize { SMALL, MEDIUM, LARGE }
CoffeeSize size;
}
public class CoffeeEnum
{
public static void main(String[] args)
{
Coffee coffee = new Coffee();
coffee.size = Coffee.CoffeeSize.MEDIUM;
System.out.println("Size of coffee mug is: " + coffee.size);
coffee.size = Coffee.CoffeeSize.SMALL;
System.out.println("Size of coffee mug is: " + coffee.size);
coffee.size = Coffee.CoffeeSize.LARGE;
System.out.println("Size of coffee mug is: " + coffee.size);
}
}
Purpose
- To show how to use Java
enumto define a set of constants (in this case, different coffee sizes). - To illustrate how to use
enumin practice by associating it with an instance of a class and displaying its values.
1. Define an enum
enum CoffeeSize { SMALL, MEDIUM, LARGE }
enum CoffeeSize: Defines three constants for coffee sizes —SMALL,MEDIUM, andLARGE.- Each constant represents a specific size.
enumhelps in defining a fixed set of related constants, which makes the code more readable and maintainable.
2. Coffee Class
class Coffee
{
enum CoffeeSize { SMALL, MEDIUM, LARGE }
CoffeeSize size;
}
- The
Coffeeclass has an instance variablesizeof typeCoffeeSize. - This
sizevariable represents the size of a coffee mug and will hold one of the values (SMALL,MEDIUM, orLARGE) from theCoffeeSizeenum.
3. Main Method
public static void main(String[] args)
{
Coffee coffee = new Coffee();
coffee.size = Coffee.CoffeeSize.MEDIUM;
System.out.println("Size of coffee mug is: " + coffee.size);
coffee.size = Coffee.CoffeeSize.SMALL;
System.out.println("Size of coffee mug is: " + coffee.size);
coffee.size = Coffee.CoffeeSize.LARGE;
System.out.println("Size of coffee mug is: " + coffee.size);
}
- Creating an Instance: A
Coffeeobject is instantiated. - Assigning Sizes:
- The
coffee.sizeis assignedCoffee.CoffeeSize.MEDIUM. - The
coffee.sizeis then changed toCoffee.CoffeeSize.SMALL. - Finally, it is set to
Coffee.CoffeeSize.LARGE.
- The
- Printing Sizes: The size of the coffee mug is printed each time it is set to a different
enumconstant.
Key Concepts
-
enumin Java:enumis a special class in Java used to define a collection of constants.- It helps in defining a clear and fixed set of related values (like
SMALL,MEDIUM, andLARGEcoffee sizes). enummakes the code easier to read and maintain since it restricts the number of possible values.
-
Encapsulation of Constants:
enumconstants can be used to enforce a controlled set of possible values, which is useful for scenarios where the set of values should be restricted and predictable.
-
Instance Variables:
- The
sizevariable in theCoffeeclass is an instance of theCoffeeSizeenum, representing the coffee's size.
- The
-
Usage in Main Method:
- Demonstrates changing and printing different sizes of coffee mugs, showing the flexibility of enums.
Output
Size of coffee mug is: MEDIUM
Size of coffee mug is: SMALL
Size of coffee mug is: LARGE