In the previous lesson we looked System.out.println().
Java Constants
Another common use of class level (i.e., static) variables is for the definition of constants. These are values which once set, cannot be changed.
In the Animal class there exists the instance variable gender which is expected to contain either "m" or "f". This means that client objects need to specify one of these Strings when creating Animal objects (i.e., the second constructor argument) or when using the setGender() method. This situation can be improved by defining two constants, one each to define male and female:
public abstract class Animal {
// Constants
public static final String MALE = "m";
public static final String FEMALE = "f";
... rest of class omitted ...
- The variables are defined as
final, which prevents their references from being changed after being initially set, and because theStringclass is immutable it is this which effectively makes them "constant" - Because these constants can never change value it is safe to make them
public. In fact, it is useful to do so as you will see shortly - They are defined as
staticbecause you only need one value which can be shared by all the animals. If you omit thestatickeyword then each instance would have its own copy of the same value, which would be wasteful of memory - Java naming conventions are that constant names are defined in upper-case, i.e.,
MALEandFEMALE - The value ("m" or "f") is assigned as part of the declaration. Had this not been done the
Stringwould default to null and it would be impossible to change thereafter (because it is a constant!) - To use the constants in client objects you need to prefix the class name to the variable name (e.g.,
Animal.MALEorAnimal.FEMALE). Within theAnimalclass itself you don't need to include the prefix since it is implied
You can now make use of the constant as follows:
Animal leo = new Lion("Leo", Animal.MALE, 3);
leo.setGender(Animal.FEMALE);
Hopefully you can see that this makes it more obvious to the reader that you are referring to a gender. The solution is not perfect, however, since there is nothing to stop client objects from still passing "m" or "f" directly. Also, client objects could still pass a nonsensical value such as "x", "abcdef" or "silly" because the argument type will accept any String. This will be addressed in the next lesson.
In the next lesson we will show how to use enum for constants.
Comments