Java OOP Guide: Tracking the Weather with Enums

  • 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:

    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:

    Kod
    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!

Şimdi katılın!

Henüz hesabınız yok mu? Topluluğumuzun aktif bir üyesi olun ve oyunlarla, yazılımlarla ilgili ilginç konuları keşfedin! Kaydolun ve tartışmalara katılın, deneyimlerinizi paylaşın ve yeni arkadaşlar edinin. Topluluğumuzda herkesin kendine göre bir yer bulabileceğinden eminiz. Hadi, gelin ve bizimle birlikte eğlenceli ve bilgilendirici bir yolculuğa çıkın!