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