fun with enums

i stumbled upon a very nasty corner-case using enums. i wont call it a puzzler, but you may want to try to predict the output of the following:

 Java |  copy |? 
public enum Person {
    PETER, PAUL, MARY;
 
    private Food favFood;
 
    Food getFavFood()
    {
        return this.favFood;
    }
 
    static void setPreference(final Person p, final Food f)
    {
        p.favFood = f;
    }
 
    public static void main(final String[] args)
    {
        final Person[] people = Person.values();
        for (int i = 0; i < people.length; i++)
        {
            final Person p = people[i];
            System.out.println(p.name() + " likes " + p.getFavFood());
        }
    }
}
 
enum Food {
    SOUP, MEAT, VEGETABLE;
 
    static
    {
        Person.setPreference(Person.MARY, SOUP);
        Person.setPreference(Person.PETER, Food.VEGETABLE);
    }
}

in order to not spoil your fun, i put the output in the comments, so that you have to click on it…

so, if you´re clever enough to spot the problem, we can take it a little further by adding

 Java |  copy |? 
static
    {
        System.out.println(Food.SOUP);
    }

to the class person and rerun it. isn´t that nice !?

i have - let´s just say 'a clue' - what is going on, but proper explainations are pretty welcome ;)

disclaimer: (JDK1.6, eclipse compiler, standard settings) ... no compiler was hurt in the process :)

4 comments to fun with enums

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>