I was exploring enums in java to see how they could be abused and I came across a behaviour I couldn\'t explain. Consider the following class:
public class PROGR
When you call ENUM.ANIMALS.CATS.GARFIELD.RIVAL
, it will start by creating the CATS enum. When processing the first element, FELIX, it needs to create the DOGS enum so that DOGS.AKAME can be passed as a parameter to the CATS constructor.
The DOGS constructor receives a parameter of type CATS, but since CATS was not yet initialized all CATS.something will return null
, thus setting the RIVAL attribute to null
for all elements in the DOGS enum.
When all DOGS elements are created, it goes back to CATS and resumes the creation of its elements, passing the just created DOGS elements as parameters.
Similarly, when you invert the order of the calls it starts by creating the DOGS enum which causes the CATS elements RIVAL attribute to be set as null
.
If this is not clear, try to run your code with breakpoints set at the enum elements' declarations and at the constructors to understand it better.