enum
replacing class
public enum Day { MONDAY("Monday"), TUESDAY("Tuesday"), ... SUNDAY("Sunday"); final String name; Day(final String name) { this.name = name;} public String toString() { return name;} }
public enum Day { ... public static String getItalianDayName(final Day day) { switch (day) { case MONDAY: return "Lunedì"; case TUESDAY: return "Martedì"; ... case SUNDAY: return "Domenica"; } return null; // Actually unreachable, but static // compiler code analysis is limited } }
public enum Day {
...
private Day(final String name)
{ ... |
Compile time warning: Modifier 'private' is redundant for |
public enum Day {
...
public Day(final String name)
{ ... |
Compile time error: Modifier 'public' not allowed here |
Prohibits enum
external instance creation.
No. 130
Compass directions
Q: |
We consider an eight direction compass rose: Provide an
TipProvide an appropriate constructor among with suitable
«internal» instance attributes and a corresponding |
||||||
A: |
The desired output contains both a given direction's oral description and a 0 - 360° degree value. We thus start by:
For creating a public enum Direction { N(0, "north"); ❶ Direction(final int degree, final String fullName) { ❷ this.degree = degree; this.fullName = fullName; } public final int degree; ❸ public final String fullName; }
For creating output texts like e.g.
|
No. 131
Compass direction neighbours
Q: |
We would like to «invert» a given direction
e.g. turning
Tip
|
||
A: |
Using a
Using the hint we may instead calculate the opposing direction:
|
No. 132
Former zodiac examination task
Q: |
Implement the zodiac task 2 from the 2024 winter examination implementation project. |