Why is an enum declared in a separate file, in Java?

Why is an enum declared in a separate file, in Java?

You don't have to declare an enum in a separate file. You could do this:

public class Temperature {
    public enum ScaleName {celsius, fahrenheit, kelvin, rankine};
    
    private double number;
    private ScaleName scale;

    public Temperature() {
        number = 0.0;
        scale = ScaleName.fahrenheit;
    }
    ...
}

The only difference between this and making the enum a top level class is that you now need to qualify the name of the enum when you use it in a different class.

But what is going on in my example is no different to what happens if the enum was any other static nested class. (A nested enum is implicitly static, so we don't need a static keyword. See JLS 8.9.)


Why is this enum declared in its own file.

Because the code author chose to do it this way1.

Is there an advantage to this?

Yes. It means that don't have to qualify the enum to use it ... in some circumstances where you would have to if the enum was nested as above.


Actually, Java does allow you to put multiple top-level classes into the same source file provided that all but one of the classes is "package private". However, doing that is generally thought to be bad style, and it can be problematic for some tool chains ... I have heard.


1 - If you want to know the real reason why the authors of the textbook chose to do it that way, you would need to ask them!


An enum is a class and follows same regulations.

Having it on its own file is exactly like moving an inner class in a separate file, nothing more nor less. So yes you can move it inside one of the class and be able to access it from outside with OuterClass.ScaleName syntax.


Enums are not just bare values in Java, they are much more than that. They are classes in their own right (they inherit Object). And consider these:

public enum Int {
    ONE(1),
    TWO(2);

    private final int value;

    Int(final int value) { this.value = value; }

    public int getValue() { return value; }

    @Override
    public String toString() { return "I am integer " + value; }
}

Consider also:

public enum Operation
{
    PLUS
        {
            @Override
            public int calculate(final int i1, final int i2)
            {
                return i1 + i2; 
            }
        };

    public abstract int calculate(int i1, int i2);
}

final int ret = Operation.PLUS.calculate(2, 3);

And you can combine them both, too. They are very powerful tools.

Tags:

Java

Enums