Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private enum location inside a class in Java [closed]

When declaring an enum inside a class in java I've seen these 2 approaches:

1)

public class MyClass {

    private enum MyEnum {
        A, B, C;
    }

    /* Static fields */

    /* Instance variables */

    /* Methods */
}

2)

public class MyClass {

    /* Static fields */

    /* Instance variables */

    /* Methods */

    private enum MyEnum {
        A, B, C;
    }
}

Which one is the most used? Is there any convention for this?

like image 915
miviclin Avatar asked Oct 12 '13 19:10

miviclin


People also ask

Can enum be private in Java?

Enum FieldsThe enum constructor must be private . You cannot use public or protected constructors for a Java enum . If you do not specify an access modifier the enum constructor it will be implicitly private .

Can we have enum inside class in Java?

Yes, we can define an enumeration inside a class. You can retrieve the values in an enumeration using the values() method.

Can you declare an enum private?

You cannot declare an enumeration within a method. To specify the appropriate level of access, use Private , Protected , Friend , or Public . An Enum type has a name, an underlying type, and a set of fields, each representing a constant.

How would you define enum inside a class?

An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).


1 Answers

Generally in Java, nested data types (e.g. classes, enums) go at the bottom of a file.

However, for short, private enums like the one you posted (which feel more like fields), I'd go with #1.

For longer enums, I'd either go with #2 or put them in a separate file.

like image 121
Joel Christophel Avatar answered Oct 11 '22 15:10

Joel Christophel