In this tutorial, we will explore the versatile concept of enums (short for enumerations) in Java. Enums are a special data type that enables a variable to be a set of predefined constants. They are particularly useful when you have a fixed set of values that a variable can take. Understanding enums is crucial as they enhance code readability and maintainability. This tutorial will cover the basics of enums, how to use them in switch statements, and how to loop through enum values.
Enums allow you to define a collection of constants that are logically related. For instance, days of the week, months, or states can be represented as enums. Using enums makes your code more readable and less error-prone by restricting variables to only predefined values.
In this section, we will delve into how enums can be used in inheritance and polymorphism, which are fundamental concepts in object-oriented programming. We'll also explore practical examples to illustrate these concepts.
An enum is a special data type that enables a variable to be a set of predefined constants. Here's a simple example:
1public enum Day {2SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;3};
In this example, Day is an enum that has seven constants representing the days of the week.
Enums are often used with switch statements to make code more readable and maintainable. Here's how you can use enums in a switch statement:
1public class Main {2public static void main(String[] args) {3Day today = Day.MONDAY;45switch (today) {6case MONDAY:7System.out.println("It's Monday!");8break;9case TUESDAY:10System.out.println("It's Tuesday!");11break;12// Add cases for other days13default:14System.out.println("It's another day.");15break;16}17}18}
It's Monday!
You can loop through all the values of an enum using the values() method, which returns an array of all the constants in the enum. Here's an example:
1public class Main {2public static void main(String[] args) {3for (Day day : Day.values()) {4System.out.println(day);5}6}7}
SUNDAY MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY
Enums in Java can extend other classes, but they must extend the Enum class. This allows you to add methods and fields to enums. Here's an example:
1public enum Day {2SUNDAY(0), MONDAY(1), TUESDAY(2), WEDNESDAY(3), THURSDAY(4), FRIDAY(5), SATURDAY(6);34private int value;56Day(int value) {7this.value = value;8}910public int getValue() {11return value;12}13}
In this example, each enum constant has an associated integer value. You can access this value using the getValue() method.
Enums can also be used in polymorphic scenarios. Here's an example where we define a base class and two derived classes:
1public abstract class Animal {2public abstract void makeSound();3}
1public class Dog extends Animal {2@Override3public void makeSound() {4System.out.println("Woof!");5}6}
1public class Cat extends Animal {2@Override3public void makeSound() {4System.out.println("Meow!");5}6}
Now, let's create an enum that represents different animals and use them in a polymorphic way:
1public class Main {2public static void main(String[] args) {3Animal myDog = new Dog();4Animal myCat = new Cat();56myDog.makeSound(); // Output: Woof!7myCat.makeSound(); // Output: Meow!8}9}
You can also define methods within each enum constant. Here's an example:
1public enum Day {2SUNDAY("It's Sunday!") {3public String getAdvice() {4return "Relax and enjoy the weekend!";5}6},7MONDAY("It's Monday!") {8public String getAdvice() {9return "Start your week with energy!";10}11};1213private final String message;1415Day(String message) {16this.message = message;17}1819public abstract String getAdvice();2021@Override22public String toString() {23return message;24}25}
In this example, each enum constant has a getAdvice() method that provides specific advice for that day. The toString() method is overridden to provide a custom string representation.
Let's create a practical example that combines enums with inheritance and polymorphism. We'll define an enum for different types of vehicles and use them in a polymorphic way.
1public abstract class Vehicle {2public abstract void start();3}
1public class Car extends Vehicle {2@Override3public void start() {4System.out.println("Car engine started.");5}6}
1public class Motorcycle extends Vehicle {2@Override3public void start() {4System.out.println("Motorcycle engine started.");5}6}
Now, let's define an enum for different types of vehicles:
1public enum VehicleType {2CAR(new Car()),3MOTORCYCLE(new Motorcycle());45private final Vehicle vehicle;67VehicleType(Vehicle vehicle) {8this.vehicle = vehicle;9}1011public void start() {12vehicle.start();13}14}
Finally, let's use the enum in a main class:
1public class Main {2public static void main(String[] args) {3VehicleType car = VehicleType.CAR;4VehicleType motorcycle = VehicleType.MOTORCYCLE;56car.start(); // Output: Car engine started.7motorcycle.start(); // Output: Motorcycle engine started.8}9}
values() method.In the next tutorial, we will explore how to handle user input in Java. We'll cover different ways to read input from the console, including using Scanner, BufferedReader, and command-line arguments. This knowledge will be essential for building interactive applications that require user interaction. Stay tuned!