Spaces:
Running
Running
File size: 1,414 Bytes
68812be |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
Next, let's write the 'GamePiece' class.
Define the class so that it cannot be inherited.
The class should have the following features:
Constructor, which takes the color (an integer) as a parameter
Get method getColor, which returns the color
import java.util.Random;
public class Test{
public static void main(String[] args){
final Random r = new Random();
System.out.println("Testing the GamePiece class...");
GamePiece p1 = new GamePiece(Color.BLACK);
System.out.println("GamePiece created");
System.out.println("GamePiece is final: " + (p1.getClass().getModifiers() > 15));
System.out.println("Calling observation method...");
System.out.println("getColor() returns " + p1.getColor());
p1 = new GamePiece(Color.WHITE);
System.out.println("GamePiece created");
System.out.println("Calling observation method...");
System.out.println("getColor() returns " + p1.getColor());
}
}
//ADD
final class GamePiece {
private int color;
// constructor
public GamePiece(int color) {
this.color = color;
}
public int getColor() {
return this.color;
}
}
Testing the GamePiece class...
GamePiece created
GamePiece is final: true
Calling observation method...
getColor() returns 2
GamePiece created
Calling observation method...
getColor() returns 1
|