Pages

Friday, 22 February 2013

Using enum

All in one place. My examples.

package enumtest;
import java.util.Random;

/**
 * @author Alex Pilugin
 */

enum Numbers{
    ONE,
    TWO,
    THREE,
    FOUR,
    FIVE,
    SIX,
    SEVEN
}

enum Deadlines{
    HOUR,
    DAY,
    WEEK,
    MONTH,
    YEAR;
    int count = 0;
    Deadlines(){
        count++;
    }
}

enum Priority{
    MIN(1),
    NORM(5),
    MAX(10);
    private Priority(int value){
        this.value = value;
    }
    public int getValue(){
        return value;
    }
    private int value;
}
 
enum Scores{
    BAD(0),
    NORMAL(5),
    GOOD(10),
    EXCELLENT(GOOD.points){
        @Override
        public int getPoints(int bonus){
            return 2 * GOOD.points + bonus;
        }
    };
    Scores(int points){
        this.points = points;
    }
    public int getPoints(int bonus){
        return points + bonus;
    }
    private int points;
}

enum Greetings{
    MORNING{
        @Override
        String say(){
            return "Good Morning";
        }
    },
    DAY{        
        @Override
        String say(){
            return "Good Afternoon";
        }
    },
    EVENING{
        @Override
        String say(){
            return "Good Evening";
        }
    },
    NIGHT{
        @Override
        String say(){
            return "Good Night";
        }
    };
     abstract String say();
}

enum Season{
    WINTER, 
    SPRING, 
    SUMMER, 
    AUTUMN;
    private int size;
    public Season getRandom(){
        Season[] s = Season.values();
        size = s.length;
        int random =  new Random().nextInt(size);
        return s[random];
    }
}

public class EnumTest {
    public static void main(String[] args) {
        Numbers n = Numbers.ONE; 
        System.out.println("Numbers: " + n);
        
        Deadlines d = Deadlines.DAY;
        System.out.println("Deadlines: " + d.DAY.count + " " + d);
        
        for(Priority p : Priority.values())
            System.out.println("Priority: " + p 
                                + "-" + p.getValue());
        
        for(Scores s : Scores.values())
            System.out.println("Scores: " + s 
                                + "-" + s.getPoints(0));
        
        for(Greetings g : Greetings.values())
            System.out.println("Greetings: " + g.say());
        
        Season season = Season.AUTUMN;
        for(int i = 0; i < 10; i++)
            System.out.println(season.getRandom()); 
       
    }
}

No comments:

Post a Comment