Java Reference
In-Depth Information
The other methods of class
Rational
perform the arithmetic operations.
public
Rational plus(Rational other) {
if
(denominator
##
other.denominator)
return new
Rational(numerator
!
other.numerator,
other.denominator);
else
return new
Rational(numerator * other.denominator
!
denominator * other.numerator,
denominator * other.denominator);
}
public
Rational minus(Rational other) {
if
(denominator
##
other.denominator)
return new
Rational(numerator - other.numerator,
denominator);
else
return new
Rational(numerator * other.denominator -
denominator * other.numerator,
denominator * other.denominator);
}
public
Rational mul(Rational other) {
return new
Rational(numerator * other.numerator,
denominator * other.denominator);
}
public
Rational div(Rational other) {
return new
Rational(numerator * other.denominator,
denominator * other.numerator);
}
public
void copyOf(Rational other) {
this
.numerator
#
other.numerator;
this
.denominator
#
other.denominator;
}
}
Class
Format
implements the generic representation format. It is declared
public in order to be visible from outside the package (e.g. from the
command line interpreter). The method
getName()
is public and is therefore
visible from outside the package, while the other two methods are visible
only from other classes belonging to the same package. These choices about
visibility are dictated by the information hiding principle, i.e. show only
what is necessary, hide all the rest. The immediate benefit of this approach
is that the interactions between the classes are clear.
public abstract class
Format {
// public members
public abstract
String getName();
// package visible member
abstract
String toString(Rational number);