Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using enums in Java across multiple classes

Tags:

I have the following class:

public class Card  {     public enum Suit      {         SPACES, HEARTS, DIAMONDS, CLUBS     };      public Card(Suit nsuit, int nrank)     {         suit = nsuit;         rank = nrank;     }      private Suit suit;     private int rank; } 

I want to instantiate it in another class, but that class doesn't understand the Suit enum. Where should I put the enum to make it publicly visible?

like image 511
Igor Avatar asked Jan 08 '11 16:01

Igor


People also ask

Can enum have multiple values Java?

Learn to create Java enum where each enum constant may contain multiple values. We may use any of the values of the enum constant in our application code, and we should be able to get the enum constant from any of the values assigned to it.

How do you create multiple enums in Java?

String[] digit = {"one", "two", "three"}; String[] teen= {"ten", "twenty", "thirty"}; String[] anchors = {"hundred", "thousand", "million"}; I'm thinking of transferring these to enums separately, so I will have 3 enum classes: digit , teen and anchors with getValue methods implemented.

Can a class have multiple enums?

java file may have only one public class. You can therefore declare only one public enum in a . java file. You may declare any number of package-private enums.


1 Answers

The Suit enum is inside the Card class, and you have to access it that way:

new Card(Card.Suit.SPADES, 1); 

Or, you can import the Suit class from within Card, and access it directly:

import my.package.Card.Suit; new Card(Suit.SPADES, 1); 

The other option is to put Suit in its own class, as suggested by Bert.

like image 65
Jorn Avatar answered Oct 05 '22 09:10

Jorn