使用枚举

时间:2015-10-21 05:20:09

标签: java enums

public class Movie {
    private String title, director;
    private float overallRating;

    private enum showingStatus {ComingSoon, Preview, NowShowing};

    public Movie(String title, enum showingStatus, String director)
    {
        this.title = title;
        this.showingStatus = showingStatus;
        this.director = director;
        overallRating = 0;
    }
}

当有人创建Movie对象时,如何以这种方式限制,他们只传入我定义的showingStatus列表?

我还想定义get和set方法,但是它们会抛出注释中指出的错误

public void setShowingStatus(enum showingStatus){ this.showingStatus = showingStatus;} // showingStatus cannot be resolved or not a field
public String getShowingStatus() { return showingStatus; } // showingStatus cannot be resolved to a variable

1 个答案:

答案 0 :(得分:2)

我认为这可能就是你要找的东西。

public class Movie {
    private String title, director;
    private float overallRating;
    private ShowingStatus showingStatus;

    public enum ShowingStatus {ComingSoon, Preview, NowShowing}

    public Movie(String title, ShowingStatus showingStatus, String director)
    {
        this.title = title;
        this.showingStatus = showingStatus;
        this.director = director;
        overallRating = 0;
    }
}

修改

这是一回事。传递变量时,不能声明enum类型。这就是你做的一切。在这种情况下,我将其设置为ShowingStatus,因此您会说:

public void setShowingStatus(ShowingStatus showingStatus){ this.showingStatus = showingStatus;} // showingStatus cannot be resolved or not a field
public ShowingStatus getShowingStatus() { return showingStatus; } // showingStatus cannot be resolved to a variable

要允许其他类使用ShowingStatus枚举,请通过执行以下操作创建单独的枚举文件:

public enum ShowingStatus {
    ComingSoon, Preview, NowShowing
}

现在,其他类应该能够在ShowingStatus中调用ShowingStatus.ComingSoon或任何其他枚举元素。