Reputation: 147
I am trying to get my head around enums, some lines of code have me slightly confused. This is taken straight from the oracle docs site but having a little trouble understanding a few lines of code :
public class EnumTest {
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
Day day;
public EnumTest(Day day) {
this.day = day;
}
The first 5 lines (class EnumTest) is quite ok, self explanatory really. What I dont understand are the last 5 lines of the above code, confusing. Could someone please explain their meaning within the context of the complete code below? Enumtest(Day day) is obviously a method , its the "this.day = day" and the preceding "Day day" I dont get .....
Complete code :
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();
}
}
Upvotes: 2
Views: 239
Reputation: 1016
Actually, it's not really a method the way you think it is. If you notice, there's a new class called EnumTest, so what you're actually seeing is the constructor. And then the line below it, this.day = day
sets the day for any instance of an object of class EnumTest
using the input into the constructor. Sample code that could run in the main method would be:
EnumTest fri = new EnumTest(Day.FRIDAY);
Since there is no return type (i.e. void or int etc.) you can tell it's a constructor. Another clue is that it has the same name is the class that holds it.
Upvotes: 6