Spaces:
Running
Running
File size: 1,516 Bytes
2884d31 | 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 | First, let's write a class called Color,
which has no other members than 2 integer class variables:
BLACK (value 2)
WHITE (value 1)
These variables must be marked with the 'final' modifier.
====================================================
import java.util.Random;
import java.lang.reflect.Field;
public class Test {
public static void main(String[] args) {
final Random r = new Random();
System.out.println("Testing the Color class...");
try {
Field white = Color.class.getDeclaredField("WHITE");
System.out.println("WHITE is final: " + (white.getModifiers() > 10));
System.out.println("WHITE, value: " + Color.WHITE);
Field black = Color.class.getDeclaredField("BLACK");
System.out.println("BLACK is final: " + (black.getModifiers() > 10));
System.out.println("BLACK, value: " + Color.BLACK);
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//ADD
class Color {
// public - allow access from other class
// static - class-level constants
// final - cannot be changed
public static final int BLACK = 2;
public static final int WHITE = 1;
}
Testing the Color class...
WHITE is final: true
WHITE, value: 1
BLACK is final: true
BLACK, value: 2
|