开发者

java enums: conceptual doubt

Consider the enum:

enum day{ MONDAY, TUESDAY};

What are monday, tuesday. the sun documentation says that they 开发者_运维百科are fields in the special class type enum. But, if that is the case, why can we do:

day d=day.MONDAY  

I mean how can we assign a class constant to a class variable.


You're assigning the value of the field to a new field. That's no different from:

public class Constants {
    public static final String FOO = "foo";
}

public class Other {
    String x = Constants.FOO;
}

The enum is just another reference type, except that it happens to have some library support, and the only instances of the enum (leaving aside some grotty hacks) are the ones referred to by the enum values.


Like @Jon's suggestion but more specificly ...

EDIT: I have added some of the methods Enum provides for you. I hope that helps...

public class Day /* extends Enum */ {
    public static final Day MONDAY = new Day("MONDAY", 0);
    public static final Day TUESDAY = new Day("TUESDAY", 1);

    private static final Day[] values = { MONDAY, TUESDAY };
    private static final Map<String, Day> valueOfMap = new HashMap();

    public static Day[] values() { return values.clone(); }
    public static Day valueOf(String name) {
        Day day = valueOfmap.get(name);
        if(day == null) throw new IllegalArgumentException(name);
        return day;
    }

    private final String name;
    private final int ordinal;

    private Day(String name, int ordinal) {
        this.name = name;
        this.ordinal = ordinal;
        valueOfMap.put(name, this);
    }
    public String name() { return name; }
    public int ordinal() { return ordinal; }
    public String toString() { return name; }
}

public class Other {
    Day day = Day.MONDAY;
}

This may not be how it is implemented but how you could implement it.


You can always assign a class constant to a class variable. Consider:

public class ConstantClass
{
    public static String constantString = "I am a constant";
}

include ConstantClass;

public class OtherClass
{
    private String regularVariable;

    public OtherClass()
    {
        regularVariable = ConstantClass.constantString;
    }
}

As with a regular class, this also applies with the enum type.


MONDAY and TUESDAY are instances of the class that is defined by the enum statement.

Here is an example:

enum dow
{
    MONDAY(1),
    TUESDAY(2);

    private int value;

    private dow(int value)
    {
        this.value = value;
    }

    public int getValue()
    {
        return value;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜