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
enum
to define a set of constants (in this case, different coffee sizes). - To illustrate how to use
enum
in 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.
enum
helps 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
Coffee
class has an instance variablesize
of typeCoffeeSize
. - This
size
variable represents the size of a coffee mug and will hold one of the values (SMALL
,MEDIUM
, orLARGE
) from theCoffeeSize
enum
.
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
Coffee
object is instantiated. - Assigning Sizes:
- The
coffee.size
is assignedCoffee.CoffeeSize.MEDIUM
. - The
coffee.size
is 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
enum
constant.
Key Concepts
-
enum
in Java:enum
is 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
, andLARGE
coffee sizes). enum
makes the code easier to read and maintain since it restricts the number of possible values.
-
Encapsulation of Constants:
enum
constants 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
size
variable in theCoffee
class is an instance of theCoffeeSize
enum
, 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