Java Reference
In-Depth Information
/** Define a static subtract method that returns a
*anew Complex object with the difference.
**/
public static Complex subtract (Complex cvalue1,
Complex cvalue2) {
double r = cvalue1.real - cvalue2.real;
double i = cvalue1.imag - cvalue2.imag;
return new Complex (r, i);
}
} // class Complex
Here the new static add() and subtract() methods each create a new complex
object to hold the sum and difference, respectively, of the two input complex
objects. The operand objects are unchanged by the method.
As we discussed in Chapter 3, a static method is invoked by giving the name
of the class and the dot operator. Unfortunately, in Java, unlike C
,wecannot
override the + operator and create a special + operator for complex addition. The
following code shows how to add two complex numbers together using our static
add() method:
++
public class ComplexTest {
public static void main (String[] args) {
// Create complex objects
Complex a = new Complex (1.0, 2.1);
Complex b = new Complex (3.3, 1.2);
Complex c = Complex.add (a, b); // c now holds a + b
... other code...
}
}
The Web Course Chapter 4 gives a more complete version of the class (e.g. it
includes modulus, multiplication, etc.).
4.9 Random number generation
Random values can be obtained from the Math class using the method
public static double random ()
This method produces pseudo-random double values in the range
0.0 <= r < 1.0
Search WWH ::




Custom Search