Java Reference
In-Depth Information
if (numberOfAdjacentMines == 1) {
mineIcon = new MineIcon(1);
} else if (numberOfAdjacentMines == 2) {
mineIcon = new MineIcon(2);
// and so on up to 8
return mineIcon;
In this case, we can assume a MineIcon class exists and that its constructor will take two integer
values and return an icon (a type of image) that shows the value of that integer argument. Because a
square in a minesweeper game can have no more than eight neighboring mines, we stop at eight. We
also let the method return null , to represent the case where a square has no neighboring mines.
Consequently, the code that calls this method then has to know what to do with a null value. As it
happens, the setIcon method that we need to use accepts a null argument as a way of saying that no
icon needs to be set.
We create a full-blown minesweeper program in Chapter 7, “Creating a User Interface.” When we
do, you see a different way to use set the mine icon, but it still uses a null reference. For now, just
remember that null is just another value (though a special one that indicates a non-existent reference)
and that it can be used for purposes other than just checking for missing objects.
An enumeration (often written as “enum”) is a data type that consists of a fixed number of constants. For
example, if you are writing a game that involves navigation, you might have an enumeration to define
the four cardinal directions, similar to the one shown in Listing 3-11.
Listing 3-11. Enum for directions
public enum Direction {
As Listing 3-11 shows, the declaration of an enumeration consists of the enum keyword, a name for
the enumeration, and the values that comprise the enumeration. The values are just names and have no
type of their own. That works because we need unique identifiers but don't need a type for each one.
The value of enumerations is that they are type-safe (meaning that it can't be confused with another
type—enums used to be created with integers, so confusing an enum with an integer was a real
problem). Without enumerations, we'd have to set up constants in a different way—usually with
integers, as shown in Listing 3-12.
Listing 3-12. Constants to define directions
public static final int NORTH = 0;
public static final int EAST = 1;
public static final int SOUTH = 2;
public static final int WEST = 3;
Search WWH ::

Custom Search