Using enums as classes. Examples of declaring enumerations containing constructors, internal fields, methods
Contents
- 1. Features of using enumerations as classes. Using constructors, fields, and methods in enumerations
- 2. Examples of using constructors, fields and methods in enumerations. Initializing data in the enumeration
- 2.1. An example of setting the number of days in a month for named constants
- 2.2. An example of using an enumeration that stores constants of the double type
- 2.3. An example of an enumeration declaration that uses two constructors
- 2.4. An example of an enumeration declaration in which the constructor receives 2 parameters
- Related topics
Search other resources:
1. Features of using enumerations as classes. Using constructors, fields, and methods in enumerations
All enumerations declared in Java program are class types and are inherited from the Enum class. This inheritance greatly expands the capabilities of enumerations. Enumerations can contain constructors, interfaces, internal fields, methods, etc. Using various constituents in the enum body works the same way as in classes. When declaring an enumeration instance, you do not need to use the new operator. Each named enumeration constant is an object of its enumeration class.
This means that when you declare a constructor in an enumeration, that constructor is called every time you create an enumeration constant. The constructor in the enumeration is used in the same way as in the class. The constructor initializes the values of the named constants of enumeration. An enumeration can contain an arbitrary number of overloaded constructors.
In a simplified form, the general form of declaring and using a constructor in enumeration is as follows:
enum EnumName { constant1(arguments1), constant2(arguments2), ... constantN(argumentsN); // Конструктор EnumName(list_of_parameters) { // ... } }
here
- EnumName – the name of enumeration type;
- constant1, constant2, constantN – named constants from the enumeration, taking the values of arguments arguments1, agruments2, argumentsN, respectively;
- EnumName(list_of_parameters) – an enumeration constructor that receives a list of parameters list_of_parameters.
Fields (internal variables) in an enumeration are mainly used to store the values of named constants. Methods in an enumeration allow you to perform various operations, calculations on fields, and access named constants. It is not prohibited in enumerations to use any number of fields and methods to perform calculations or other actions.
⇑
2. Examples of using constructors, fields and methods in enumerations. Initializing data in the enumeration
2.1. An example of setting the number of days in a month for named constants
Task.
The Months enumeration is specified. Use the constructor to set each month to the number of days in that month.
Solution.
// An enumeration describing the months of the year enum Months { // Named constants - months of the year January(31), February(28), March(31), April(30), May(31), June(30), July(31), August(31), September(30), October(31), November(30), December(31); // Constructor required to initialize named constants (Jauary, February, ...) with integer values Months(int nDays) { this.nDays=nDays; } // The field that stores the number of days // for example, for the constant January (31), the value nDays = 31 private int nDays; // Method that returns the number of days public int getNDays() { return nDays; } } public class TrainEnumerations { public static void main(String[] args) { // Create an instance of the Months type and initialize it with a value Months mn = Months.April; // Print the number of days in the constant mn.April System.out.println(mn.getNDays()); // Print the number of days in the constant Months.September System.out.println(Months.September.getNDays()); } }
Let’s explain the execution of the above code. In the above example, each constant is initialized to an integer value (January (31), February (28), …) using the constructor
Months(int nDays) { this.nDays=nDays; }
The value of the number of days is stored in a hidden (private) internal field
private int nDays;
In order to read the nDays field in the client code, you need to create a public method in the body of the Months enumeration
// Method that returns the number of days public int getNDays() { return nDays; }
The above approach allows you to correctly store and get values of any type in named enumeration constants.
The result of the program
30 30
⇑
2.2. An example of using an enumeration that stores constants of the double type
Task.
Demonstrate the use of well-known mathematical constants in the MathConstants enumeration. Use constants to perform calculations.
Solution.
As you know, each enumeration constant is an object (instance) of the type of this enumeration. Therefore, in order to store constants of type double, you need to create an appropriate constructor. This constructor will receive a double value parameter that will initialize the constant.
For each constant, you need to store a value, therefore, an additional internal private variable is introduced into the enumeration code, which will store this value.
The text of the program that solves this problem is as follows
import java.util.Scanner; // An enumeration containing mathematical constants of type double. enum MathConstants { Pi(3.1415), Exp(2.71), G(9.81); // Internal field that stores the value of a constant private double value; // Constructor - needed to initialize constants with values, for example: Pi(3.1415) MathConstants(double x) { value = x; } // The method is needed to get the value of the constant public double Value() { return value; } } public class TrainEnumerations { public static void main(String[] args) { // Using floating point constants in enums // 1. Declare an enumeration MathConstants mc; // 2. To use the constant G, you must call the Value() method. mc = MathConstants.G; System.out.println("G = " + mc.Value()); // G = 9.81 // 3. Use the constant Pi to calculate the volume of the sphere from the entered radius Scanner inputDouble = new Scanner(System.in); System.out.print("radius = "); double radius = inputDouble.nextDouble(); double volume = 4.0/3*MathConstants.Pi.Value()*radius*radius*radius; System.out.println("volume = " + volume); } }
Test example
G = 9.81 radius = 4 volume = 268.07466666666664
⇑
2.3. An example of an enumeration declaration that uses two constructors
Enumeration constants can be initialized in a variety of ways. Several suitable constructors are declared for this.
The example, for demonstration purposes, initializes the values of named constants in different ways.
// An enumeration in which named constants are initialized with different constructors enum Character { // Named constants A('A'), // constructor with 1 parameter is called B('B'), // constructor with 1 parameter is called Enter('\n'), // constructor with 1 parameter is called SpaceBar; // constructor with no parameters is called // Constructor that receive one parameter Character(char _symbol) { symbol = _symbol; } // Constructor with no parameters, sets the "space" character Character() { symbol = ' '; // the spacebar } // Internal variable storing a character private char symbol; // Access method to the variable symbol public char getSymbol() { return symbol; } } public class TrainEnumerations { public static void main(String[] args) { // 1. Set an instance of an enum of type Character Character ch = Character.B; // 2. Print the value of the instance ch System.out.println(ch.getSymbol()); // B } }
⇑
2.4. An example of an enumeration declaration in which the constructor receives 2 parameters
The example declares a PaperSize enumeration that describes the formats of letters by their size. The size of each sheet is set by two parameters: width and height. Accordingly, the constants from the enumeration get two values. To initialize these values, the enumeration declares a constructor that receives 2 parameters.
The demo program text is as follows
// Enumeration describing paper sizes A1, A2, A3, A4, ... enum PaperSize { // Paper sizes A1(594, 841), A2(420, 594), A3(297, 420), A4(210, 297), A5(148, 210), A6(105, 148), A7(74, 105); // Constructor with 2 parameters PaperSize(int width, int height) { this.width = width; this.height = height; } // Internal variables - dimensions of a sheet of paper private int width, height; // Access methods public int getWidth() { return width; } public int getHeight() { return height; } } public class TrainEnumerations { public static void main(String[] args) { // Using the PaperSize enumeration PaperSize ps = PaperSize.A2; // Display width and height System.out.println("Format " + ps.name() + ":"); System.out.println("width = " + ps.getWidth() + " height = " + ps.getHeight()); } }
Результат выполнения программы
Format A2: width = 420 height = 594
⇑
Related topics
- Enumerations. Keyword enum. Examples
- Class Enum. Methods: clone(), compareTo(), getDeclaringClass(), hashCode(), name(), ordinal(), toString()
⇑