Java Enumeration Q&A (Need to know about Java Q&A Article Series 2)

Hüseyin K.
6 min readNov 1, 2022

--

Hi Java people.

I am Huseyin. Have been a .Net developer for years and Java backend and Android developer for 6 years as well as a QA Automation Engineer team member for several projects for 3 years.

Have been getting a reasonable amount of questions from any level of Java developers for years. In the end, decided to write my own answers instead of spending my time over the same thing again and again. As a developer, by experiencing the reusability, abstraction and the maintainability issues for years, I decided to implement the same structure in my life and abstract myself from answering similar questions 🙂. Thus, put my effort into creating this “Need to know about Java Q&A Article Series”. By doing so, I am comfortable about answering similar questions by just sending a link to these articles 🙂. It helped me to understand many very important concepts of Java as well.

The target audience of “Need to know about Java Q&A Article Series” is the ones who already know coding with Java, but also want to improve his/her knowledge or to prepare for Java Interviews. If you are a new bee, I believe these articles may be a couple of levels higher for you.

Main purpose of these articles is not to explain topics in detail. Of course there are a lot of sources about Java on the internet. What I experienced is that some different approaches while explaining the same thing helps people to understand the topics. What I am trying to do is actually that. A different kind of explanation.

Articles are prepared by Question & Answer structure which I do believe is an efficient way of learning.

If these articles help you to understand a concept, I definitely feel very happy. Feel free to share and comment.

Sharing is learning at the same time! Enjoy.

What is Enum?

Java 5 introduced the enum keyword. It denotes a special type of class that always extends the java.lang.Enum class. The Enum in Java is a data type which contains a fixed set of constants. The Java enum constants are static and final implicitly.

Constants defined this way make the code more readable, allow for compile-time checking, document the list of accepted values upfront, and avoid unexpected behavior due to invalid values being passed in. You should use enum types anytime you need to represent a fixed set of constants.

Give examples of general Enum usage in applications

I commonly use days of week as enum, because they are constant. Why I am using enum is: Using final variable declarations instead of enums for constant values is error prone since there is no compile-time checking applied to this kind of structure.

By using enum I am forcing the method parameters to be an enum instance in order to avoid typing errors in this case. By defining a finite set of values, the enum is more type safe than constant literal variables like String or int. Another common usage in my project is Category and Sub-Category enums which are constant too.

Is Enum extensible? Can Enum implement an interface?

When enums are compiled they are turned into a subclass of the abstract class java.lang.Enum and they are compiled as final class. As we know, we can’t inherit a final class in Java. So we can’t create a subclass of an existing enum. As noted all enums internally extend java.lang.Enum, so enum cannot extend any other class because Java does not support multiple class inheritance this way.

Enums can implement interfaces. If we implement the same interface with two different enums we can use the interface as a reference type for accessing the implemented functionality in both enums like we do with regular classes.

How is Enum used in switch-case?

Using Java Enum in the Switch case is pretty straightforward. Just use the Enum reference variable in Switch statement and Enum constants or instances in Case statements.

For example, let’s think about the Color enum which has RED and GREEN as constant instances. In a switch case block we use Color instance in the switch expression, then we use RED and GREEN constant instances in two different cases.

What are the some predefined methods in Enum?

  • Built-in valueOf(String name) method returns the corresponding enum constant instance by the provided enum instance name as String.
  • Another built-in valueOf(Class<T> enumType, String name) method, which accepts the type name and the searched enum instance name as string, returns the corresponding enum instance from the provided type.
  • Built-in values() method of the Enum returns an array of the defined enum instances.

Can Enum declare constructors?

Enums can have constructors.

There can be a question like that; if Enum instances are predefined instances, what is the point of using a constructor in Enum?

An enum type has no instances other than those defined by its enum constants. It is a compile-time error to attempt to explicitly instantiate an enum type with the new keyword like we do for non-abstract classes.

But, Enums can have instance fields like classes. That is why we can define constructors in Enums. Because, if the enum has instance fields, there should be a constructor to initialize them (first value assignment). Since enums are constant, their fields are constant as well.

We can use enum constants (pre-defined enum instances) to call the constructor for field initializations. For this purpose, enum constructors can be private or package-private. But, they can not be public since it is not allowed to create an instance of enum outside of it. That’s why we can not use the new keyword, since the constructors of the enums are only accessible within its own context.

Using the public access modifier will cause compile time error. Using a new keyword for creating a new enum instance will also cause compile time error, too.

In an enum declaration with no constructor declarations, a default constructor is implicitly declared. The default constructor is private, has no formal parameters, and has no throws clause. Moreover, a constructor declaration with no access modifiers is private.

How can we create an Enum constant value, and access them?

Enum values are required to be valid identifiers, but, we’re encouraged to use SCREAMING_SNAKE_CASE by convention. Take this in mind, given those limitations, the enum value alone is not suitable for human-readable strings or non-string values. Enum constant instances can simply be created like that;

public enum Element {    H, HE, LI, BE, B, C, N, O, F, NE}

These enum instances can be accessed via type name like;

Element.H

As it is said, while the uppercase form is appropriate for Java constants, it’s not how we normally write the symbols. Furthermore, we’re also missing other properties of the periodic table elements, like the name and atomic weight. For making Element enum much efficient, we can add a couple of instance fields and we can initialize them through a constructor like this;

For accessing a property of an Enum instance, we can call that property through the enum instance like that;

Element.H.getWeight();

Thanks for reading. Hope this helps! See you in the next articles.

PS: Really benefited from especially Baeldung and other Java Tutorial Websites, as well as Official Java Documentation.

Dedicated to Dirty Java Rangers

--

--

Hüseyin K.
Hüseyin K.

No responses yet