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

                274 Chapter 7 Object-Oriented Programming—Additional Details
in Figure 7.12 we inserted a call to a previously written method that already had the code we wanted. You do the same thing with constructors; that is, you can call a previously written constructor from within another constructor. Constructor calls are different from method calls in that they use the reserved word new, which tells the JVM to allocate space in memory for a new object. Within the original constructor, you could use the new operator to call another constructor. But that would create a separate object from the original ob- ject. And most of the time, that’s not what you want. Normally, if you call an overloaded constructor, you want to work with the original object, not a new, separate object.
 1 /**************************************************************
2 *
3 *
4*
5
Fraction.java
Dean & Dean
This class stores and prints fractions.
**************************************************************/
6
7
8
public class Fraction
9{
*
10 private int numerator;
11 private int denominator;
12 private double quotient;
13 Apago PDF Enhancer
14 //***********************************************************
15
16 public Fraction(int n)
17 {
18 this(n, 1);
19 }
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
   //***********************************************************
public Fraction(int n, int d)
}
// end class Fraction
{
}
this.numerator = n;
this.denominator = d;
this.quotient = (double) this.numerator / this.denominator;
//***********************************************************
public void printIt()
{
System.out.println(this.numerator + " / " +
this.denominator + " = " + this.quotient);
} // end printIt
This statement calls the other constructor.
Figure 7.19
Fraction class with overloaded constructors





















































   306   307   308   309   310