哪里使用枚举类型
我必须创建自己的日历类(我知道已经存在一个,但我们需要编写自己的日历类,因此我无法使用预先存在的 Calendar
或 GregorianCalendar 中的任何方法
类),并且我们需要使用枚举类型。我不确定我会用它们做什么,因为我对它们不太熟悉。
如果有帮助,我的构造函数会采用日期、月份和年份值(例如 2011 年 5 月 8 日)。
I have to create 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).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
枚举是处理相同类型的有限值集时的首选武器。例如:
这使得它们的使用强类型。
您可以指定接受枚举作为参数的方法,例如:
另一种方法是使用字符串(或整数)常量,通常称为字符串类型,但此类常量不是类型化的 - 接受字符串的方法将接受 >any 字符串 - 例如“Foo”:
枚举可以(大部分)像普通类一样使用 - 你可以有构造函数(私有)、字段和方法,如下所示:
你甚至可以有设置器,因为枚举不必须是不可变(它们的字段不必是最终的),但不建议这样做。
编辑:更多信息
枚举不能
扩展
,但它们可以实现
,因此如果您有多个月份类型(针对不同的日历),您可以这样做以保持强类型。这是日历和月份的抽象示例enums are the weapon of choice when dealing with a finite set of values of the same type. For example:
This makes the use of them strongly typed.
You can specify methods to accept enum as parameters, eg:
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":
enum can be used (mostly) like normal classes - you can have constructors (private), fields and methods, like this:
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 canimplements
, 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您的第一站应该是 Java enum 教程,我认为很好地解释了它们是什么以及何时需要使用它们。
除此之外,简短的答案是,您可以将它们用于任何值可以是特定(有限)数量的常量之一的情况。我确信您可以想到至少一个与日历相关的字段,该字段被限制在一定范围的有效值(尽管您不允许使用内置日历,但如果您想要一些日历,请看一下它们)提示)。
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).