Java Reference
In-Depth Information
Example 2•5: ComplexNumber.java (continued)
* This is a static class method. It takes two complex numbers, adds
* them, and returns the result as a third number. Because it is static,
* there is no "current instance" or "this" object. Use it like this:
* ComplexNumber c = ComplexNumber.add(a, b);
**/
public static ComplexNumber add(ComplexNumber a, ComplexNumber b) {
return new ComplexNumber(a.x + b.x, a.y + b.y);
}
/**
* This is a non-static instance method by the same name. It adds the
* specified complex number to the current complex number. Use it like
* this:
* ComplexNumber c = a.add(b);
**/
public ComplexNumber add(ComplexNumber a) {
return new ComplexNumber(this.x + a.x, this.y+a.y);
}
/** A static class method to multiply complex numbers */
public static ComplexNumber multiply(ComplexNumber a, ComplexNumber b) {
return new ComplexNumber(a.x*b.x - a.y*b.y, a.x*b.y + a.y*b.x);
}
/** An instance method to multiply complex numbers */
public ComplexNumber multiply(ComplexNumber a) {
return new ComplexNumber(x*a.x - y*a.y, x*a.y + y*a.x);
}
}
Computing Pseudo-Random Numbers
So far, all the classes we've defined have represented real-world objects. (A com-
plex number is an abstract mathematical concept, but it's not too hard to think of
it as a real-world object.) In some cases, however, you need to create a class that
doesn't represent some kind of object, or even an abstract concept. Example 2-6,
which defines a class that can compute pseudo-random numbers, is just this kind
of class.
The Randomizer class obviously doesn't implement some kind of object. It turns
out, however, that the simple algorithm used to generate pseudo-random numbers
requires a state variable, seed , that stores the random-number seed. Because you
need to keep track of some state, you can't simply define a static random()
method, as you did for methods such as Factorial.factorial() in Chapter 1.
When a method requires state to be saved between one invocation and the next,
the method typically needs to be an instance method of an object that contains the
necessary state, even if the object itself has no obvious real-world or abstract
counterpart.
Thus, our Randomizer class defines a single instance variable, seed , that saves the
necessary state for generating pseudo-random numbers. The other fields in Ran-
domizer are declared static and final , which makes them constants in Java. In
Search WWH ::




Custom Search