Java Reference
In-Depth Information
Class
Card
Class
Card
(Fig. 7.9) contains two
String
instance variables—
face
and
suit
—that are
used to store references to the face name and suit name for a specific
Card
. The constructor
for the class (lines 10-14) receives two
String
s that it uses to initialize
face
and
suit
.
Method
toString
(lines 17-20) creates a
String
consisting of the
face
of the
card
, the
String
"of"
and the
suit
of the card.
Card
's
toString
method can be invoked
explicitly
to obtain a string representation of a
Card
object (e.g.,
"Ace of Spades"
). The
toString
method of an object is called
implicitly
when the object is used where a
String
is expected
(e.g., when
printf
outputs the object as a
String
using the
%s
format specifier or when
the object is concatenated to a
String
using the
+
operator). For this behavior to occur,
toString
must be declared with the header shown in Fig. 7.9.
1
// Fig. 7.9: Card.java
2
// Card class represents a playing card.
3
4
public class
Card
5
{
6
private
final
String face;
// face of card ("Ace", "Deuce", ...)
7
private
final
String suit;
// suit of card ("Hearts", "Diamonds", ...)
8
9
// two-argument constructor initializes card's face and suit
10
public
Card(String cardFace, String cardSuit)
11
{
12
this
.face = cardFace;
// initialize face of card
13
this
.suit = cardSuit;
// initialize suit of card
14
}
15
16
// return String representation of Card
public
String toString()
{
return
face +
" of "
+ suit;
}
17
18
19
20
21
}
// end class Card
Fig. 7.9
|
Card
class represents a playing card.
Class
DeckOfCards
Class
DeckOfCards
(Fig. 7.10) declares as an instance variable a
Card
array named
deck
(line 7). An array of a
reference
type is declared like any other array. Class
DeckOfCards
also
declares an integer instance variable
currentCard
(line 8) representing the sequence num-
ber (0-51) of the next
Card
to be dealt from the
deck
array, and a named constant
NUMBER_OF_CARDS
(line 9) indicating the number of
Card
s in the deck (52).
1
// Fig. 7.10: DeckOfCards.java
2
// DeckOfCards class represents a deck of playing cards.
3
import
java.security.SecureRandom;
4
Fig. 7.10
|
DeckOfCards
class represents a deck of playing cards. (Part 1 of 2.)