By Tony Bevis on Monday, 09 October 2023
Category: Java

Java programming course: 5.3 Constants

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:


You can now make use of the constant as follows:

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.

Next lesson: 5.4 Using enum for constants

Related Posts

Leave Comments