TurkuBasicOOPinJava / Week 6: Methods of OO Programming /14B. The Last Piece, Part 1: The Color Class
KaiquanMah's picture
public static final int VARIABLE = 2;
2884d31 verified
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