我试图让我的脑袋围绕枚举,一些代码行让我有些困惑。 这可以直接从oracle docs站点获取,但在理解几行代码时遇到一些麻烦:
public class EnumTest {
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
Day day;
public EnumTest(Day day) {
this.day = day;
}
前5行(EnumTest类)非常好,非常自我解释。我不明白的是上面代码的最后5行,令人困惑。有人可以在下面的完整代码的上下文中解释它们的含义吗? Enumtest(Day day)显然是一种方法,它的“this.day = day”和之前的“Day day”我没有得到.....
完整代码:
public class EnumTest {
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
Day day;
public EnumTest(Day day) {
this.day = day;
}
public void tellItLikeItIs() {
switch (day) {
case MONDAY:
System.out.println("Mondays are bad.");
break;
case FRIDAY:
System.out.println("Fridays are better.");
break;
case SATURDAY: case SUNDAY:
System.out.println("Weekends are best.");
break;
default:
System.out.println("Midweek days are so-so.");
break;
}
}
public static void main(String[] args) {
EnumTest firstDay = new EnumTest(Day.MONDAY);
firstDay.tellItLikeItIs();
EnumTest thirdDay = new EnumTest(Day.WEDNESDAY);
thirdDay.tellItLikeItIs();
EnumTest fifthDay = new EnumTest(Day.FRIDAY);
fifthDay.tellItLikeItIs();
EnumTest sixthDay = new EnumTest(Day.SATURDAY);
sixthDay.tellItLikeItIs();
EnumTest seventhDay = new EnumTest(Day.SUNDAY);
seventhDay.tellItLikeItIs();
}
}
答案 0 :(得分:6)
实际上,它并不像你想象的那样是一种方法。如果你注意到,有一个名为EnumTest的新类,那么你实际看到的是构造函数。然后在它下面的行this.day = day
使用输入到构造函数中为类EnumTest
的任何对象实例设置日期。可以在main方法中运行的示例代码是:
EnumTest fri = new EnumTest(Day.FRIDAY);
由于没有返回类型(即void或int等),您可以告诉它是构造函数。另一个线索是它具有相同的名称是持有它的类。