Java Reference
In-Depth Information
IntegerMatrix
GenericMatrix<E extends Number>
#add(element1: E, element2: E): E
#multiply(element1: E, element2: E): E
#zero(): E
+addMatrix(matrix1: E[][], matrix2: E[][]): E[][]
+multiplyMatrix(matrix1: E[][], matrix2: E[][]): E[][]
+
printResult(m1: Number[][], m2: Number[][],
RationalMatrix
m3: Number[][], op: char): void
F
IGURE
19.7
The
GenericMatrix
class is an abstract superclass for
IntegerMatrix
and
RationalMatrix
.
Integer
type and
0/1
for the
Rational
type. These methods will be implemented in the
subclasses in which the matrix element type is specified.
IntegerMatrix
and
RationalMatrix
are concrete subclasses of
GenericMatrix
.
These two classes implement the
add
,
multiply
, and
zero
methods defined in the
GenericMatrix
class.
Listing 19.10 implements the
GenericMatrix
class.
<E extends Number>
in line 1
specifies that the generic type is a subtype of
Number
. Three abstract methods—
add
,
multiply
,
and
zero
—are defined in lines 3, 6, and 9. These methods are abstract because we cannot imple-
ment them without knowing the exact type of the elements. The
addMaxtrix
(lines 12-30) and
multiplyMatrix
(lines 33-57) methods implement the methods for adding and multiplying
two matrices. All these methods must be nonstatic, because they use generic type
E
for the class.
The
printResult
method (lines 60-84) is static because it is not tied to specific instances.
The matrix element type is a generic subtype of
Number
. This enables you to use an object
of any subclass of
Number
as long as you can implement the abstract
add
,
multiply
, and
zero
methods in subclasses.
The
addMatrix
and
multiplyMatrix
methods (lines 12-57) are concrete methods.
They are ready to use as long as the
add
,
multiply
, and
zero
methods are implemented in
the subclasses.
The
addMatrix
and
multiplyMatrix
methods check the bounds of the matrices before
performing operations. If the two matrices have incompatible bounds, the program throws an
exception (lines 16, 36).
L
ISTING
19.10
GenericMatrix.java
1
public abstract class
GenericMatrix<E
extends
Number> {
2
bounded generic type
/** Abstract method for adding two elements of the matrices */
3
protected abstract
E add(E o1, E o2);
abstract method
4
5
/** Abstract method for multiplying two elements of the matrices */
6
protected abstract
E multiply(E o1, E o2);
abstract method
7
8
/** Abstract method for defining zero for the matrix element */
9
protected abstract
E zero();
abstract method
10
11
/** Add two matrices */
12
public
E[][] addMatrix(E[][] matrix1, E[][] matrix2) {
13
// Check bounds of the two matrices
14
if
((matrix1.length != matrix2.length) ||
15 (matrix1[
0
].length != matrix2[
0
].length)) {
16
add two matrices
throw new
RuntimeException(
17
"The matrices do not have the same size"
);
18 }
19
Search WWH ::
Custom Search