Hello, dear Jetto Net forum members!
In the previous post, I explained the basic features and usage of Enums in Java. In this post, we will create a simple program that stores temperature values for each day using constructors, fields, and methods, and performs different operations based on these values.
Let's get started:
First, let's create an enum class and start assigning values:
enum Days {
// Assigning temperature values next to each day.
MONDAY(25),
TUESDAY(28),
WEDNESDAY(30),
THURSDAY(27),
FRIDAY(26),
SATURDAY(24),
SUNDAY(22);
private int temperature;
Days(int temperature) {
this.temperature = temperature;
}
public int getTemperature() {
return temperature;
}
public String getWeatherCondition() {
if (temperature < 20) {
return "Cold";
} else if (temperature >= 20 && temperature < 30) {
return "Mild";
} else {
return "Hot";
}
}
}
Daha Çok Göster
Here, I defined each day with a constant value and corresponding temperature values. The constructor (Days(int temperature)) will be used to assign temperature values when enum constants are created.
The temperature field will hold the temperature value for each day. The getTemperature() method will return the temperature variable (getter). The getWeatherCondition() method will return the weather condition based on the temperature.
Now, with the main method, we can get the day from the enum class and return the temperature value:
public class Main {
public static void main(String[] args) {
Days today = Days.MONDAY;
System.out.println("Today: " + today);
System.out.println("Temperature: " + today.getTemperature() + "°C");
System.out.println("Weather Condition: " + today.getWeatherCondition());
}
}
I assigned a value from our enum class to the today variable. We retrieved the temperature value and weather condition using the getTemperature() and getWeatherCondition() methods. When we run the program, the output in the console will look like this:
In this example, we saw how to make an enum more powerful by adding constructors, fields, and methods. This allows us to use enums not only for immutable values but also to store additional information related to those values and perform operations.
I hope this content has helped you understand Enums better. Feel free to write your questions or comments in the comments section.
Happy Coding!