public class Game {
// Rest of the game class remains the same. Omitting...
public static boolean play(Player p, Pile pile) {
int sticksTaken = p.takeTurn(pile);
System.out.println("\n" + p.getName() + " takes " + sticksTaken + " sticks.\n" +
"There are " + pile.getSticks() + " left in the pile.");
if (p instanceof GreedyPlayer) {
((GreedyPlayer) p).jeer(); // Print the GreedyPlayer's message
}
if (pile.getSticks() <= 0) {
return true;
}
return false;
}
}
Console.charset()
if the Console
exists,
stdout.encoding otherwise.
Console.charset()
if the Console
exists,
stdout.encoding otherwise.
For simple stand-alone Java applications, a typical way to write a line of output data is:
System.out.println(data)
See the println
methods in class PrintStream
.
Since the static type of p
is still Player
, we first do a
type-cast to obtain a different "view" of the object that p
points to. We want to look at it as a GreedyPlayer
.
We know this is safe because we just passed the instanceof
check on the previous line.
Since the static type of p
is still Player
, we first do a
type-cast to obtain a different "view" of the object that p
points to. We want to look at it as a GreedyPlayer
.
We know this is safe because we just passed the instanceof
check on the previous line.
Having obtained a reference of type GreedyPlayer
, we are now able to invoke
GreedyPlayer
-specific behaviours, like jeer
.
Having obtained a reference of type GreedyPlayer
, we are now able to invoke
GreedyPlayer
-specific behaviours, like jeer
.
This added block of code prints out the GreedyPlayer
's jeer
each time they take a turn.
This added block of code prints out the GreedyPlayer
's jeer
each time they take a turn.
The instanceof
keyword checks if the operand on the left (some expression that evaluates to
an object of some type) is an instance of the operand on the right (some reference type).
By "instance of" we mean: is the data type of the left-hand side an exact match or child
type of the right-hand-side?
The instanceof
keyword checks if the operand on the left (some expression that evaluates to
an object of some type) is an instance of the operand on the right (some reference type).
By "instance of" we mean: is the data type of the left-hand side an exact match or child
type of the right-hand-side?