Page 299 - Introduction to Programming with Java: A Problem Solving Approach
P. 299

                Figure 7.11 HeightDriver class that drives the Height class in Figure 7.10
Figure 7.12 Example of method that calls another method in the same class This helps avoid duplication of code details and possible internal inconsistencies.
When they want to use the improved method, all they have to remember is the original method name and adding a second argument, for units, to the method call. That’s an al- most obvious variation, and it’s easier to remember than a different method name. It’s cer- tainly easier than being forced to learn a new method name for the old task—which would be a necessary cost of upgrading if method overloading were not available.
7.8 Constructors
Up to this point, we have used mutators to assign values to the instance variables in newly instantiated objects. That works OK, but it requires having and calling one mutator for each instance variable. As an al- ternative, you could use a single method to initialize all of an object’s instance variables as soon as possible after you create that object. For example, in this chapter’s Car class in Figure 7.2, instead of defining three mutator methods, you could define a single initCar method to initialize Car objects. Then you could use it like this:
Car allexCar = new Car();
7.8 Constructors 265
 /*******************************************************************
*
HeightDriver.java
Dean & Dean
This class is a demonstration driver for the Height class.
*******************************************************************/
*
*
*
public class HeightDriver
{
}
// end class HeightDriver
public static void main(String[] args)
{
}
Height myHeight = new Height();
myHeight.setHeight(72.0, "in");
myHeight.print();
myHeight.setHeight(180.0);
myHeight.print();
// end main
         Apago PDF Enhancer
public void setHeight(double height)
  Do not put a reference variable dot prefix here.
 {
}
setHeight(height, "cm");
    allexCar.initCar("Porsche", 2006, "beige");
Keep it simple by re-using good names.






























































   297   298   299   300   301