TurkuBasicOOPinJava / Week 6: Methods of OO Programming /15. The Last Piece, Part 2: The GamePiece Class
KaiquanMah's picture
final class Class1 {...}
68812be verified
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