You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: source/ch6_definingclasses.ptx
+17-12Lines changed: 17 additions & 12 deletions
Original file line number
Diff line number
Diff line change
@@ -300,11 +300,11 @@ public Fraction(Integer num, Integer den) {
300
300
However, if you reassign the parameter to a completely new object inside the method (e.g., <c>otherFrac = new Fraction(0,1);</c>), it would <em>not</em> affect the original variable outside the method, because you are only changing the local copy of the reference.
301
301
</p>
302
302
<p>
303
-
Let’s begin by implementing addition in Java:
303
+
<xrefref="java-fraction-class-addition-initial"text="type-global"/> shows the first part of the Fraction class definition.
@@ -315,6 +315,7 @@ public Fraction add(Fraction otherFrac) {
315
315
}
316
316
</code>
317
317
</program>
318
+
</listing>
318
319
319
320
<p>
320
321
First you will notice that the <c>add</c> method is declared as <c>public Fraction</c> The <c>public</c> part means that any other method may call the <c>add</c> method.
@@ -324,11 +325,11 @@ public Fraction add(Fraction otherFrac) {
324
325
<p>
325
326
Second, you will notice that the method makes use of the <c>this</c> variable.
326
327
In this method, <c>this</c> is not necessary, because there is no ambiguity about the <c>numerator</c> and <c>denominator</c> variables.
327
-
So the following version of the code is equivalent:
328
+
<xrefref="java-fraction-class-addition-equivalent"text="type-global"/> is an equivalent version of <xrefref="java-fraction-class-addition-initial"text="type-global"/>.
@@ -339,6 +340,7 @@ public Fraction add(Fraction otherFrac) {
339
340
}
340
341
</code>
341
342
</program>
343
+
</listing>
342
344
343
345
<p>
344
346
The addition takes place by multiplying each numerator by the opposite denominator before adding.
@@ -385,11 +387,11 @@ public Fraction add(Fraction otherFrac) {
385
387
To solve the problem of adding an <c>Integer</c> and a <c>Fraction</c> in Java we will overload both the constructor and the <c>add</c> method.
386
388
We will overload the constructor so that if it only receives a single <c>Integer</c> it will convert the <c>Integer</c> into a <c>Fraction</c>.
387
389
We will also overload the <c>add</c> method so that if it receives an <c>Integer</c> as a parameter it will first construct a <c>Fraction</c> from that integer and then add the two <c>Fractions</c> together.
388
-
The new methods that accomplish this task are as follows:
390
+
<xrefref="java-method-overloading"text="type-global"/> shows the new methods that accomplish this task.
0 commit comments