Page 307 - Introduction to Programming with Java: A Problem Solving Approach
P. 307
Why the (double) cast? Without it, we’d get integer division and truncation of fractional values. The cast converts numerator into a double, the double numerator promotes the denominator instance vari-
7.9 Overloaded Constructors 273
10
11
12
13
14
15
16
17
18
public static void main(String[] args)
{
1 /********************************************************
2 *
3 *
4*
5
FractionDriver.java
Dean & Dean
This driver class demonstrates the Fraction class.
********************************************************/
6
7
8
public class FractionDriver
9{
*
}
// end class FractionDriver
Sample session:
3 / 4 = 0.75
3 / 1 = 3.0
Fraction a = new Fraction(3, 4);
⎫ ⎬
calls to overloaded constructors
}
Fraction b = new Fraction(3); ⎭ a.printIt();
b.printIt();
// end main
Figure 7.18
FractionDriver class which drives Fraction class in Figure 7.19 Apago PDF Enhancer
able to double, floating-point division occurs, and fractional values are preserved. Our
cast to double also provides a more graceful response if the denominator is zero. Integer di-
vision by zero causes the program to crash. But floating-point division by zero is acceptable. Instead of crash- ing, the program prints “Infinity” if the numerator is positive or “-Infinity” if the numerator is negative.
For a whole number like 3, we could call the above two-parameter constructor with 3 as the first argument and 1 as the second argument. But we want our Fraction class to be friendlier. We want it to have another (overloaded) constructor which has just one parameter. This one-parameter constructor could look like this:
Make it robust.
}
public Fraction(int n)
{
this.numerator = n;
this.denominator = 1;
this.quotient = (double) this.numerator;
Calling a Constructor from within Another Constructor
The two constructors above contain duplicate code. Duplication makes programs longer. More importantly, it introduces the possibility of inconsistency. Earlier we used over- loaded methods to avoid this kind of danger. Instead of repeating code as in Figure 7.10,
Avoid duplicate code.