Java Reference
In-Depth Information
The concat method of the String class is an example of this situation. The
method is executed through one String object and is passed another String
object as a parameter. For example:
str3 = str1.concat(str2);
The String object executing the method ( str1 ) appends its characters to those
of the String passed as a parameter ( str2 ). A new String object is returned as a
result and stored as str3 .
The RationalTester program shown in Listing 7.3 demonstrates a similar
situation. A rational number is a value that can be represented as a ratio of two
integers (a fraction). The RationalTester program creates two objects represent-
ing rational numbers and then performs various operations on them to produce
new rational numbers.
LISTING 7.3
//********************************************************************
// RationalTester.java Author: Lewis/Loftus
//
// Driver to exercise the use of multiple Rational objects.
//********************************************************************
public class RationalTester
{
//-----------------------------------------------------------------
// Creates some rational number objects and performs various
// operations on them.
//-----------------------------------------------------------------
public static void main (String[] args)
{
RationalNumber r1 = new RationalNumber (6, 8);
RationalNumber r2 = new RationalNumber (1, 3);
RationalNumber r3, r4, r5, r6, r7;
System.out.println ("First rational number: " + r1);
System.out.println ("Second rational number: " + r2);
if (r1.isLike(r2))
System.out.println ("r1 and r2 are equal.");
else
System.out.println ("r1 and r2 are NOT equal.");
r3 = r1.reciprocal();
System.out.println ("The reciprocal of r1 is: " + r3);
Search WWH ::




Custom Search