hoang
hoang

Reputation: 1594

Why Java don't force to use final with enum properties

Let's take a look with my enum definition here:

public enum Day {
    MONDAY(1),
    TUESDAY(2),
    WEDNESDAY(3);

    int index;

    Day(int i) {
        index = i;
    }

    public void setIndex(int index) {
        this.index = index;
    }

    public static void main(String[] args) {
        Day x = MONDAY;
        Day y = MONDAY;
        x.setIndex(2);
        System.out.println(y.index);  // Ouput: 2
    }

In general, I know we should not implement code like that. To prevent this, why java don't use final for final int index like Java treat with interface's properties. Does anyone can explain that?

Upvotes: 4

Views: 1013

Answers (2)

Stephen C
Stephen C

Reputation: 719229

Questions like "Why Java doesn't force to use of final for enum properties" have only one correct answer:

Because the Java designers did not design it that way.

We can only speculate as to why they didn't design it that way. The only people who really know the actual reasons are the designers themselves. And the chances are that even they wouldn't be able to remember all of the details of their decision making. (I wouldn't be able to.) There could in theory still be minutes of design meetings sitting in the bottom of someone's filing cabinet, but they are not accessible to us ... now.

My speculation is that the designers would have thought of plausible use-cases where enum values with mutable properties would be useful. And as @Sweeper points out, enum-based implementation of the singleton design pattern is one such use-case. Even the example that @aeberhart quotes in his answer can be read another way:

While fields of an enum do not have to be final, in the majority of cases we don't want our labels to change.

implies that in a minority of cases, they could want the labels to change. That's an argument for NOT requiring the label field in the example (and fields in general) to always be final ... at the language level.

To generalize, it is not a good thing for a program language design to not support (or forbid) constructs and usage patterns just because the designers don't like it. Or just because certain (so-called) experts endorse them as "best practice".

Upvotes: 4

aeberhart
aeberhart

Reputation: 899

It is best practice to use final, but (unfortunately) not enforced by the compiler.

This tutorial (https://www.baeldung.com/java-enum-values) states this as follows:

"Our label field is final. While fields of an enum do not have to be final, in the majority of cases we don't want our labels to change. In the spirit of enum values being constant, this makes sense."

Upvotes: 1

Related Questions