Java Reference
In-Depth Information
In a similar way, engineers could use objects to represent the different com-
ponents that make up a complex machine or a group of machines like a power
plant. Each object representing a component of a system can act and interact
with the other objects of the system. A modified or enhanced component can
then correspond to an extended class (see Chapter 4).
3.10.1 Complex number class
Fortran, the long time programming language in science, includes a complex
number type, but Java, unfortunately, does not. As mentioned earlier we can,
however, create a complex class of our own. A complex number needs two mem-
ory locations reserved for the real and imaginary parts and it needs methods to
carry out operations such as addition and subtraction.
Below we show code for a complex number class that possesses two floating-
point fields for the real and imaginary values plus two methods to carry out
operations on these values:
/** A very limited complex class. **/
public class BasicComplex
{
double real;
double img;
/** Constructor initializes the values. **/
BasicComplex (double r, double i)
{ real = r; img = i; }
/** Define a complex add method. **/
public void add (BasicComplex cvalue) {
real = real + cvalue.real;
img = img + cvalue.img;
}
/** Define a complex subtract method. **/
public void subtract (BasicComplex cvalue) {
real = real cvalue.real;
img = img cvalue.img;
}
}
Then in another program we could create two instances of our complex class and
add one to the other, as shown below:
 
Search WWH ::




Custom Search