Usando enumeraciones en Java en múltiples clases

Tengo la siguiente clase:

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?

preguntado el 08 de enero de 11 a las 16:01

Por cierto, el ; after your Suit decl is unnecessary. -

4 Respuestas

Put Suit in its own class:

Suit.java:

public enum Suit 
{
    SPACES, HEARTS, DIAMONDS, CLUBS
}

Respondido el 08 de enero de 11 a las 19:01

Thanks. I've been thinking about that but I thought that all classes needed the class keyword. - Igor

@Richard - Yeah, it was surprising to me the first time I saw it. - Bert F

This does solve the problem, but I don't think it's the best solution. The Suit enum belongs in the Card class, since you'll always use them together. - Jorn

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.

Respondido el 08 de enero de 11 a las 19:01

The enum is already visible.

Card card = new Card(Card.Suit.CLUBS, 5);

will instantiate a new card.

Unrelated... but you might want to make the Spaces suit into the Spades suit. :)

Respondido el 08 de enero de 11 a las 19:01

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

Card.Suit suit = Card.Suit.CLUBS;

Respondido el 18 de Septiembre de 14 a las 11:09

error: unexpected type required: class,package found: variable - msysmilu

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.