Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should Java enums be defined in their own files?

If I've understood enums correctly, a good example would be to use them to store the suite of a playing card instead of four magic numbers or four static final ints.

public class Card {
    // ...
    private enum CARD_SUITE { HEARTS, DIAMONDS, CLUBS, SPADES; }
}

But what if a public method of Card needs a suite as argument, e.g. isSuite(CARD_SUITE suite)? The enumeration is private to the class. Making a new file for that single line feels very unnecessary. How is this solved?

like image 389
Andreas Avatar asked Dec 20 '22 00:12

Andreas


1 Answers

You can make it public in the same class, only public class should be defined in a separate Java file.

public class Card {
    // ...
    public enum CARD_SUITE { HEARTS, DIAMONDS, CLUBS, SPADES; }
}

You can then access the enum like Card.CARD_SUITE.HEARTS, Card.CARD_SUITE.DIAMONDS...

like image 52
Jayamohan Avatar answered Jan 07 '23 01:01

Jayamohan