javatypesenumsenumsetenum-map

Is there something like nested enums in Java?


I want to do a Country enum from which i can access to its states, how can i do that?

Something like this:

public enum SomeEnum {

     ARGENTINA {
       BUENOS_AIRES;
     }

     UNITED_STATES {
       CALIFORNIA, FLORIDA, NEW_YORK, ALASKA;
     }

}

SomeEnum state1 = SomeEnum.ARGENTINA.BUENOS_AIRES
SomeEnum state2 = SomeEnum.UNITED_STATES.CALIFORNIA;

Solution

  • You could use a interface like

    interface Country {
        Country USA = Americas.USA;
    
        enum Asia implements Country {
            Indian,
            China,
            SriLanka
        }
        enum Americas implements Country {
            USA,
            Brazil
        }
        enum Europe implements Country {
            UK,
            Ireland,
            France
        }
    }
    

    and you can have

    Country c = Country.USA;
    c = Country.Asia.China;