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.