Using enums in Java across multiple classes
I have the following class:
public class Card
{
public enum Suit
{
SPACES, HEARTS, DIAMONDS, CLUBS
};
public Card(Suit nsuit, int nrank)
{
suit = nsuit;
开发者_如何学Python 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?
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.
Put Suit in its own class:
Suit.java:
public enum Suit
{
SPACES, HEARTS, DIAMONDS, CLUBS
}
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. :)
The Suit
enum is inside the Card
class, and you have to access it that way:
Card.Suit suit = Card.Suit.CLUBS;
精彩评论