开发者

Where to use enumerated types

I have to cre开发者_JS百科ate my own calendar class (I know one already exists, but we are required to write our own, so I cant use any of the methods from the pre-existing Calendar or GregorianCalendar classes), and we are required to use enum types. I'm not sure what I would use these for, as I am not too familiar with them.

If it helps, my constructors take a date, month, and year value (e.g. 5, 8, 2011).


enums are the weapon of choice when dealing with a finite set of values of the same type. For example:

public enum Month {
    JANUARY,
    FEBRUARY,
    MARCH,
    APRIL,
    ... etc
}

This makes the use of them strongly typed.

You can specify methods to accept enum as parameters, eg:

private Month month;
public void setMonth(Month month) {
    this.month = month;
}

The alternative is to use String (or int) contants, often called stringly typed, but such constants are not typed - methods accepting Strings will accept any String - eg "Foo":

private String month;
public void setMonth(String month) {
    this.month = month; // Will accept "Foo"
}

enum can be used (mostly) like normal classes - you can have constructors (private), fields and methods, like this:

public enum Month {
    JANUARY("January",
    FEBRUARY("February",
    ... 
    DECEMBER("December");

    private final name;

    private Month(String name) { // Constructors must be private
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

You can even have setters, because enum are do not have to be immutable (their fields do not have to be final), but it's not advised.

EDITED: More info

enums can not extends but they can implements, so if you had multiple Month types (for different Calendars) you could do this to keep strong typing. Here's and example of an abstraction of Calendar and Month

interface Month {
}

enum GregorianMonth implements Month {
}

enum ChineseMonth implements Month {
}

abstract class Calendar<T extends Enum<T> & Month> { // T must be both an enum and a Month
    T month;

    void setMonth(T month) {
        this.month = month;
    }
}

class GregorianCalendar extends Calendar<GregorianMonth> {

}

class ChineseCalendar extends Calendar<ChineseMonth> {

}


Your first stop should be the Java enum tutorial, which I think does a good job of explaining what they are, and when you'd want to use them.

The short answer beyond that is that you'd use them for anything where a value can be one of a certain (finite) number of constants. I'm sure you can think of at least one calendar-related field which is constrained to a certain range of valid values (and though you're not allowed to use the built-in calendars, take a look at them if you want some hints).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜