23

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?

1
  • 3
    BTW, the ; after your Suit decl is unnecessary. Commented Jan 8, 2011 at 16:51

4 Answers 4

31

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.

Sign up to request clarification or add additional context in comments.

Comments

25

Put Suit in its own class:

Suit.java:

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

3 Comments

Thanks. I've been thinking about that but I thought that all classes needed the class keyword.
@Richard - Yeah, it was surprising to me the first time I saw it.
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.
6

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. :)

Comments

-5

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

Card.Suit suit = Card.Suit.CLUBS;

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.