You are currently viewing Java enum Constructor with Example

Java enum Constructor with Example

In this tutorial, you will learn about Java enum Constructor with Example. Make sure you’re familiar with Java enums before going into enum constructors.

What is Java enum Constructor?

The int field is set by the enum constructor. An int value is supplied to the enum constructor when the constant enum values are defined. The constructor for the enum must be private. A Java enum cannot have public or protected constructors.

In Java, an enum class, like any other class, can have a constructor. These enum constructors are one of two types:

  • private – accessible within the class or package.
  • package-private – only available 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 BedSize;

   // private enum constructor
   private Size(String BedSize) {
      this.BedSize = BedSize;
   }

   public String getSize() {
      return BedSize;
   }
}

class Main {
   public static void main(String[] args) {
      Size size = Size.SMALL;
      System.out.println(size.getSize());
   }
}

Output

The size is small.
  • We built an enum Size in the preceding example. A private enum constructor is included. The constructor accepts a string value as a parameter and sets the variable BedSize to that value.
  • We can’t access the constructor from outside the class because it’s private. To invoke the constructor, though, we can utilize enum constants.
  • We assigned SMALL to an enum variable size in the Main class. The constructor Size is then called with string as an argument by the constant SMALL.
  • Finally, we used size to call getSize().

Enums do not require constructor definitions by default, and their default values are always the string used in the declaration. You can, however, provide your own constructors to initialize the state of enum types.

  • We can, for example, add an angle attribute to direction. Every direction has an angle. So let’s include them.
enum with constructor
public enum Direction 
{
    // enum fields
    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;
    }
}

We can access the angle for any direction by using a simple method called in the enum field reference.

Output:

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

Enum collections: EnumSet and EnumMap

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

EnumSet class is defined as follows:

public abstract class EnumSet<E extends Enum<E>>
extends AbstractSet<E>
implements Cloneable, Serializable {

//…..
}

For use with enum types, a specialized Set implementation. When an enum set is created, all of the elements must come from a single enum type that is specified, either explicitly or implicitly.

EnumSet Example

public class Test
{
public static void main(String[] args)
{
Set enumSet = EnumSet.of( Direction.EAST,
Direction.WEST,
Direction.NORTH,
Direction.SOUTH
);


}
}

EnumSet is not synchronised, like most collection implementations. If more than one thread accesses an enum set at the same time and at least one of them modifies it, the set should be synchronized externally.

There are no null elements allowed. Furthermore, these sets ensure that the elements in the set are ordered according to the order in which the enumeration constants are declared. In comparison to a traditional set implementation, the performance and memory benefits are substantial.

EnumMap

EnumMap’s declaration is as follows:

public class EnumMap<K extends Enum<K>,V> extends AbstractMap<K,V> implements Serializable, Cloneable {
}

A Map implementation tailored for use with enum type keys. In addition, all of the keys in an enum map must come from a single enum type that is specified when the map is created, either explicitly or implicitly.

Null keys, like EnumSet, are not allowed and are not synchronised.

 EnumMap Example

public class Test
{
public static void main(String[] args)
{
//Keys can be only of type Direction
Map enumMap = new EnumMap(Direction.class);

//Populate the Map 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());
}
}

It’s important to note that enum constructors should be declared as private. Although the compiler allows non-private constructors, the reader should be aware that new can never be used with enum types.

You may like:

Java Inheritance with Example | Types of inheritance

Java final Keyword with Example

Not Equal Example in Java

Java Polymorphism with Example

Singleton Class in Java with Implementation and Example

Java Nested and Inner Class with Example

Hope this article will guide you to recognize all about Java enum constructor with an Example that you needed and still if you have any problem or queries regarding this, post them in the comments section and we will be glad to assist you.

This Post Has 5 Comments

Leave a Reply