Java enum Constructor
Before you learn about enum constructors, make sure to know about Java enums.
In Java, an enum class may include a constructor like a regular class. These enum constructors are either
- private — accessible within the class
or - package-private — accessible within the package
Example: enum Constructor
enum Size < // enum constants calling the enum constructors SMALL("The size is small."), MEDIUM("The size is medium."), LARGE("The size is large."), EXTRALARGE("The size is extra large."); private final String pizzaSize; // private enum constructor private Size(String pizzaSize) < this.pizzaSize = pizzaSize; >public String getSize() < return pizzaSize; >> class Main < public static void main(String[] args) < Size size = Size.SMALL; System.out.println(size.getSize()); >>
In the above example, we have created an enum Size . It includes a private enum constructor. The constructor takes a string value as a parameter and assigns value to the variable pizzaSize .
Since the constructor is private , we cannot access it from outside the class. However, we can use enum constants to call the constructor.
In the Main class, we assigned SMALL to an enum variable size . The constant SMALL then calls the constructor Size with string as an argument.
Finally, we called getSize() using size .
Table of Contents
Enum Types
An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.
Because they are constants, the names of an enum type’s fields are in uppercase letters.
In the Java programming language, you define an enum type by using the enum keyword. For example, you would specify a days-of-the-week enum type as:
You should use enum types any time you need to represent a fixed set of constants. That includes natural enum types such as the planets in our solar system and data sets where you know all possible values at compile timefor example, the choices on a menu, command line flags, and so on.
Here is some code that shows you how to use the Day enum defined above:
public class EnumTest < 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(); >>
Mondays are bad. Midweek days are so-so. Fridays are better. Weekends are best. Weekends are best.
Java programming language enum types are much more powerful than their counterparts in other languages. The enum declaration defines a class (called an enum type). The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type. For example, this code from the Planet class example below iterates over all the planets in the solar system.
for (Planet p : Planet.values())
Note: All enums implicitly extend java.lang.Enum . Because a class can only extend one parent (see Declaring Classes), the Java language does not support multiple inheritance of state (see Multiple Inheritance of State, Implementation, and Type), and therefore an enum cannot extend anything else.
In the following example, Planet is an enum type that represents the planets in the solar system. They are defined with constant mass and radius properties.
Each enum constant is declared with values for the mass and radius parameters. These values are passed to the constructor when the constant is created. Java requires that the constants be defined first, prior to any fields or methods. Also, when there are fields and methods, the list of enum constants must end with a semicolon.
Note: The constructor for an enum type must be package-private or private access. It automatically creates the constants that are defined at the beginning of the enum body. You cannot invoke an enum constructor yourself.
In addition to its properties and constructor, Planet has methods that allow you to retrieve the surface gravity and weight of an object on each planet. Here is a sample program that takes your weight on earth (in any unit) and calculates and prints your weight on all of the planets (in the same unit):
public enum Planet < MERCURY (3.303e+23, 2.4397e6), VENUS (4.869e+24, 6.0518e6), EARTH (5.976e+24, 6.37814e6), MARS (6.421e+23, 3.3972e6), JUPITER (1.9e+27, 7.1492e7), SATURN (5.688e+26, 6.0268e7), URANUS (8.686e+25, 2.5559e7), NEPTUNE (1.024e+26, 2.4746e7); private final double mass; // in kilograms private final double radius; // in meters Planet(double mass, double radius) < this.mass = mass; this.radius = radius; >private double mass() < return mass; >private double radius() < return radius; >// universal gravitational constant (m3 kg-1 s-2) public static final double G = 6.67300E-11; double surfaceGravity() < return G * mass / (radius * radius); >double surfaceWeight(double otherMass) < return otherMass * surfaceGravity(); >public static void main(String[] args) < if (args.length != 1) < System.err.println("Usage: java Planet "); System.exit(-1); > double earthWeight = Double.parseDouble(args[0]); double mass = earthWeight/EARTH.surfaceGravity(); for (Planet p : Planet.values()) System.out.printf("Your weight on %s is %f%n", p, p.surfaceWeight(mass)); > >
If you run Planet.class from the command line with an argument of 175, you get this output:
$ java Planet 175 Your weight on MERCURY is 66.107583 Your weight on VENUS is 158.374842 Your weight on EARTH is 175.000000 Your weight on MARS is 66.279007 Your weight on JUPITER is 442.847567 Your weight on SATURN is 186.552719 Your weight on URANUS is 158.397260 Your weight on NEPTUNE is 199.207413
Previous page: Questions and Exercises: Nested Classes
Next page: Questions and Exercises: Enum Types
Enum in java with constructor
В примере, где было показано, как программисты выкручивались до появления такой замечательной конструкции, как enum, необходимо добавить модификатор `final` к переменным, иначе теряется весь смысл. Похоже, что этот момент просто упустили. Если мы говорим об именованных константах, то они всегда должны быть public static final (именно такими они и являются в классах-перечислениях).
В первом же примере, про то как в «Java 1.5 программистам приходилось, откровенно говоря, выкручиваться» с помощью класса и приватного конструктора, сами константы объявлены как public static Month, без final, видимо опечатка
насколько я понимаю Enum должен быть приват статик константой, что с геттерами и сеттерами неоч сходится, а иначе зачем вообще создавать жесткое ограничение выбора
System.out.println(Month.FEBRUARY); // Month Month.FEBRUARY.setDaysCount(10); Month.FEBRUARY.setName("Ololo"); System.out.println(Month.FEBRUARY); // Month
«Ну, например, старая конструкция не позволяла нам применять свой набор значений в switch-выражениях.» Не совсем понял. У меня, к примеру, есть public final class Constants, в котором есть статические публичные константы: и я спокойно могу его использовать в свиче: Т.е. в части enum и моего класса констант (с приватным конструктром, который я явно сделал, чтобы нельзя было создавать объекты) разницы нет. В обоих случаях я спокойно использую в свичах. Что я не так понял? Основная моя идея — сделать классы-справочники, чтобы они содержали уникальные данные (переменные), к котором я могу обращаться, чтобы использовать в своих нуждах. Что в таком случае лучше: енам или справочник-класс-констант? Пытаюсь в реальной жизни определить круг использования енам.
Java Enum with Constructor Example
Many Java developers don’t know that Java Enum can have a constructor to pass data while creating Enum constants. This feature allows you to associate related data together. One example of passing arguments to enum Constructor is our TrafficLight Enum where we pass the action to each Enum instance e.g. GREEN is associate with go, RED is associated with stop, and ORANGE is associated with the slow down.
This is really useful because it provides more context and meaning to your code. If you want, you can also provide one or more constructors to your Enum as it also supports constructor overloading like normal Java classes. This is very different from the enum you have seen in C or C++, which is just a collection of fixed things without any OOP power.
Just remember that constructor in enums an only be either private or package level it can’t be public or protected hence access modifier public and protected are not allowed to Enum constructor, it will result in a compile-time error.
By the way, this is not our first tutorial on Java Enum where we have explained a key feature, we have also ready covered some important features on Enum in our previous examples like Java Enum Switch Example explains that you can use enum constants inside switch block.
Similarly, Java Enum valueOf Example and Enum to String Example explain that how you can get the String representation of Enum. These short tutorials are a good way to learn some useful features of enum in Java.
Java Enum with Constructor Example
Here is a complete code example of using Constructor with Java Enum. Here is our TrafficLight constructor accepts a String argument which is saved to action field which is later accessed by getter method getAction().
As I explained, we have an Enum TrafficSignal, which has three enum constants, RET, GREEN, and ORANGE, and we have associated, wait, go and slow down with them by passing values into the constructor. You can also see these free Java Programming courses to learn more about enum in Java.
/**
* Java enum with the constructor for example.
* Constructor accepts one String argument action
*/
public enum TrafficSignal <
//this will call enum constructor with one String argument
RED ( «wait» ) , GREEN ( «go» ) , ORANGE ( «slow down» ) ;
private String action ;
public String getAction () <
return this . action ;
>
// enum constructor — can not be public or protected
TrafficSignal ( String action ) <
this . action = action ;
>
>
/**
*
* Java Enum example with the constructor.
* Java Enum can have a constructor but it can not
* be public or protected
*
* @author http://java67.com
*/
public class EnumConstructorExample
public static void main ( String args [])
//let’s print name of each enum and there action
// — Enum values() examples
TrafficSignal [] signals = TrafficSignal. values () ;
for ( TrafficSignal signal : signals ) <
//Java name example — Java getter method example
System. out . println ( «name : »
+ signal. name ()
+ » action: »
+ signal. getAction ()) ;
>
This was our Java Enum example with Constructor. Now, you know that Enum can have a constructor in Java that can be used to pass data to Enum constants, just like we passed action here. Though Enum constructor cannot be protected or public, it can either have private or default modifier only.
Thanks for reading this article so far. If you like this short tutorial then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.