|
July 2004 Technical Tip – Using Objects in Place of Primitives in Java If one were to create a Java class to store information about a person, one would probably use a char to indicate the gender, as in 'M' or 'F'. But there are problems with this approach. For example, there may be nothing to keep the user of this class from passing an 'X' as the gender. There is a better way. One can create a class Gender, with static instances MALE and FEMALE, and use an instance of that class (rather than a char) within the person class. First, let's illustrate the problem...here's a typical approach to the problem of storing a gender:
And this simple test application shows what's wrong with that approach. There's nothing to prevent the user of this class from specifying an invalid gender:
Here is the recommended alternative to stated problem. First, create a class Gender as follows:
Note that the constructor is private. Further, note that MALE and FEMALE are static instances of this class, therefore there will only ever be one of each. These instantiations take place within the Gender class itself, therefore they have access to the private constructor. This class is then used to indicate the gender in the Person2 class (rather than use a char) as follows:
A Person2 is instantiated by passing a String name and a Gender as shown in the following test application:
Other examples can be found at http://www.caliberdt.com/tips/Face.java, http://www.caliberdt.com/tips/Coin.java, and http://www.caliberdt.com/tips/CoinTest.java. If you or your staff are in need of Java training, we hope you’ll consider Caliber Data Training when you are looking for a training provider. Go to the articles index. Written by Bill Qualls. Copyright © 2004 by Caliber Data Training 800.938.1222 |