Is it still relevant to replace enumeration structures with classes in Java?
•
Java
I'm reading the effective java written by Joshua Bloch in 2008. A hint is to replace enumeration structures with classes This is an example from the book
public class Suit { private final String name; public Suit(String name) { this.name = name; } public String toString() { return name; } public static final Suit CLUBS = new Suit("clubs"); public static final Suit DIAMONDS = new Suit("diamonds"); public static final Suit HEARTS = new Suit("hearts"); public static final Suit SPADES = new Suit("spades"); }
My question is that Java now supports enumeration types. Is it a good idea to use the above method? The following is an example of Java enumeration types
public enum Day { SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY }
Solution
The book "effective Java" was well written before introducing enumeration into the language, so I recommend using enumeration Fortunately, Java enumeration is very versatile, so you can use the enumeration function to pay close attention to Joshua's suggestions:
public enum Day { SUNDAY("Sunday",0),MONDAY("Monday",1),TUESDAY("Tuesday",2),WEDNESDAY("Wednesday",3),THURSDAY("Thursday",4),FRIDAY("Friday",5),SATURDAY("Saturday",6); private String name; private int ordinal; public String getName() { return name; } public int getOrdinal() { return ordinal; } public Day(String name,int ordinal) { this.name = name; this.ordinal = ordinal; } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码