Pages

Tuesday, May 29, 2012

Java - Enumerated types

To enumerate some constant values, and/or associate to them methods or values, we can use enum in java. Enum types in Java are considered like classes, they can have constructors too, can implement interfaces, but can have no descendants. Let see, how we work with enum in java, through an example that classifies programming languages.
Create your own test class, and then test the following code:

    private enum prog_language {
        //enumerated constants
        java(true), c(true), basic(true), php(true), delphi(true), csharp(false), cplus(false);
       
        //fields to associate with the enum types
        private int position;
        private boolean usedbyme;
       
        //constructor
        prog_language(boolean bUsedByMe) {
            usedbyme = bUsedByMe;
        }           
        //getters and setters of the fields
        public int getPosition() {
            return position;
        }
        public void setPosition(int position) {
            this.position = position;
        }          
        public boolean isUsedbyme() {
            return usedbyme;
        }       
    };

.......................................       
        int i = 0;
        for (prog_language p : prog_language.values()) {
            i++;
            p.setPosition(i);
        }                              
        System.out.print(prog_language.valueOf("java").name());      
        System.out.println(" - at position: "+prog_language.valueOf("java").getPosition());
        System.out.println("I am using this language: "+prog_language.valueOf("java").isUsedbyme());

   
 
Enum types can also participate in switch-case statements too.

No comments:

Post a Comment