Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: is it permissible to change Enum fields at runtime? [duplicate]

Tags:

java

enums

Let's say I have an Enum with BOB and ALICE and I'm storing their age in a field. Can I have methods within the enum that change their age? It seems the compiler takes it but are there any risks / is it bad practice? So for instance:

public enum Friends {
    BOB(14),
    ALICE(22);

    private int age;

    private Friends(int age){
        this.age = age;
    }

    public void setAge(int age){
        this.age = age;
    }

    public int getAge(){
       return age;
    }
}
like image 783
alex314159 Avatar asked May 22 '26 08:05

alex314159


1 Answers

Java: is it permissible to change Enum fields at runtime?

You cannot change the Enum itself but yes you can change any field defined in a enum value.

Can I have methods within the enum that change their age? It seems the compiler takes it but are there any risks / is it bad practice?

Yes you can but it seems a clumsy use of Enums.

Enums are designed to represent a stable and fixed enumeration of "things".
You can consider them as constants.
From the Oracle documentation :

An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.

Because they are constants, the names of an enum type's fields are in uppercase letters.

With Java Enums, these things may themselves be described by properties.

When you define your enum, you do it :

public enum Friends {
    BOB(14),
    ALICE(22);

    private int age;

    private Friends(int age){
        this.age = age;
    }

Your things are some Friends and age is a property of Friend.
The problem with your enum is that your things seem not to be stable things : the friendship is something that moves and the property you use to describe the enum : age is not a stable thing either.

In your example, your Friends look like instances with a state.
So defining classes (opposed to Enum) to represent Friends and instantiating and modifying them in the client code seems a more natural way to represent and act on them.

like image 116
davidxxx Avatar answered May 23 '26 20:05

davidxxx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!