Java any enum parameter

Java Enum Tutorial

Java enum, also called Java enumeration type, is a type whose fields consist of a fixed set of constants. The very purpose of an enum is to enforce compile-time type safety. The enum keyword is one of the reserved keywords in Java.

We should use an enum when we know all possible values of a variable at compile time or design time, though we can add more values in the future as and when we identify them. In this java enum tutorial, we will learn what enums are and what problems they solve.

Enumerations (in general) are generally a set of related constants. They have been in other programming languages like C++ from the beginning. After JDK 1.4, Java designers decided to support it in Java also, and it was officially released in JDK 1.5 release.

The enumeration in Java is supported by keyword enum . The enums are a special type of class that always extends java.lang.Enum.

1.1. The enum is a Reserved Keyword

The enum is a reserved keyword which means we cannot define a variable with the name enum . e.g. It will result in compile time error «invalid VariableDeclaratorId» .

enum is reserved keyword

1.2. Syntax to Create Enums

As we know, generally we deal with four directions in daily life. Their names, angles and other properties are fixed. So, in programs, we can create an enum for them. The syntax to create an enum is as below:

Logically, each enum is an instance of enum type itself. So given enum can be seen as the below declaration. JVM internally adds ordinal and value methods to this class which we can call while working with an enum.

final class Direction extends Enum

By convention, enums are constants. In Java, constants are defined in all UPPER_CASE letters. This follows for enums also.

  • Enum name should be in title case (same as class names).
  • Enum fields should be in all UPPER CASE (same as static final constants).

We can create a variable of specified enum type just like we use final static class fields.

Direction north = Direction.NORTH; System.out.println(north); //Prints NORTH

By default, enums don’t require constructor definitions and their default values are always the string used in the declaration. Though, you can give define your own constructors to initialize the state of enum types.

For example, we can add angle attribute to direction. All directions have some angle.

enum Direction < EAST(0), WEST(180), NORTH(90), SOUTH(270); // constructor private Direction(final int angle) < this.angle = angle; >// internal state private int angle; public int getAngle() < return angle; >>

If we want to access the angle for any direction, we can make a simple method call in the enum field reference.

Direction west = Direction.WEST; System.out.println(west); System.out.println(west.getAngle()); //or System.out.println(Direction.WEST.getAngle());

By default, an enum will have the following methods to access its constants.

The ordinal() method returns the order of an enum instance among the list of constants. It represents the sequence in the enum declaration, where the initial constant is assigned an ordinal of ‘0’ . It is very much like array indices.

Ordinal is designed for use by sophisticated enum-based data structures, such as EnumSet and EnumMap .

Direction.EAST.ordinal(); //0 Direction.NORTH.ordinal(); //2

The enum values() method returns all the enum values as an enum array.

Direction[] directions = Direction.values(); for (Direction d : directions)

The enum valueOf() method helps to convert a string to an enum instance.

Direction east = Direction.valueOf("EAST"); System.out.println(east);

Remember that an enum is basically a special class type, and can have methods and fields just like any other class. We can add methods that are abstract as well as non-abstract methods. Both methods are allowed in the enum.

Adding a concrete method in an enum is similar to adding the same method in any other class. We can use any access specifier e.g. public , private or protected . We can return values from enum methods or simply use them to perform internal logic.

Читайте также:  Программы для сборки java программы

We can call the message() method as a simple method call on an enum instance.

We can also add abstract methods in enums. In this case, we must implement the abstract method at each enum field, individually.

public enum Direction < EAST < @Override public String message() < return "You are moving in east. You will face sun in morning time."; >>, WEST < @Override public String message() < return "You are moving in west. You will face sun in evening time."; >>, NORTH < @Override public String message() < return "You are moving in north. Sea behind."; >>, SOUTH < @Override public String message() < return "You are moving in south. Sea ahead."; >>; public abstract String message(); >
Direction.WEST.message(); //You are moving in west. You will face sun in evening time. Direction.NORTH.message(); //You are moving in north. Sea behind.

We can enforce a contract for all enums to be created in this way. It can serve as a template for enum creation.

For example, If we want that each enum type of Direction should be able to print the direction name with a custom message when needed. This can be done by defining a abstract method inside Direction , which each enum has to override.

As mentioned earlier, enum extends Enum class. The java.lang.Enum is an abstract class. This is the common base class of all Java enumeration types.

public abstract class Enum> extends Object implements Constable, Comparable, Serializable < //. >

It means that all enums are comparable and serializable implicitly. Also, all enum types in Java are singleton by default.

As noted all enums extends java.lang.Enum , so enum cannot extend any other class because Java does not support multiple inheritance this way. But enums can implement any number of interfaces.

All enums are by default comparable and singletons as well. It means you can compare them with equals() method, even with «= wp-block-code»> Direction east = Direction.EAST; Direction eastNew = Direction.valueOf(«EAST»); System.out.println( east == eastNew ); //true System.out.println( east.equals( eastNew ) ); //true

We can compare enum types using ‘==’ operator or equals() method, because enums are singlton and comparable by default.

Two classes have been added to java.util package in support of enums – EnumSet (a high-performance Set implementation for enums; all members of an enum set must be of the same enum type) and EnumMap (a high-performance Map implementation for use with enum keys).

Читайте также:  Load csv file in python

EnumSet class is a specialized Set implementation for use with enum types. All of the elements in an enum set must come from a single enum type that is specified, explicitly or implicitly, when the set is created.

Set enumSet = EnumSet.of(Direction.EAST, Direction.WEST, Direction.NORTH, Direction.SOUTH );

Like most collection implementations EnumSet is not synchronized. If multiple threads access an enum set concurrently, and at least one of the threads modifies the set, it should be synchronized externally.

Note that null elements are not permitted in EnumSet. Also, these sets guarantee the ordering of the elements in the set based on their order in the enumeration constants is declared. Performance and memory benefits are very high in comparison to a regular set implementation.

EnumMap is a specialized Map implementation for use with enum type keys. Also, all of the keys in an enum map must come from a single enum type that is specified, explicitly or implicitly, when the map is created.

Like EnumSet , null keys are not permitted and is not synchronized as well.

Map enumMap = new EnumMap(Direction.class); enumMap.put(Direction.EAST, Direction.EAST.getAngle()); enumMap.put(Direction.WEST, Direction.WEST.getAngle()); enumMap.put(Direction.NORTH, Direction.NORTH.getAngle()); enumMap.put(Direction.SOUTH, Direction.SOUTH.getAngle());

In this article, we explored the Java enum from the language basics to more advanced and interesting real-world use cases.

Источник

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 time—for 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.

Читайте также:  Java add arrays to arraylist

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

Источник

Оцените статью