Java Reference
In-Depth Information
4.8 Improved complex number class
In the Chapter 3 we created a class with the bare essentials needed to represent
complex numbers. Here we expand on that class. For example, we would often
like to add two complex numbers and put the sum into another complex number
rather than modify one of the current complex objects. Because of overloading we
can still use the add() method name. A new, improved version of our complex
number class appears here:
public class Complex {
double real;
double imag;
/** Constructor that initializes the real & imag values
**/
Complex (double r, double i) {
real = r; imag = i;
}
/** Getter methods for real & imaginary parts **/
public double getReal ()
{return real;}
public double getImag ()
{return imag;}
/** Define an add method **/
public void add (Complex cvalue) {
real = real + cvalue.real;
imag = imag + cvalue.imag;
}
/** Define a subtract method. **/
public void subtract (Complex cvalue) {
real = real - cvalue.real;
imag = imag - cvalue.imag;
}
/** Define a static add method that returns a
*anew Complex object with the sum.
**/
public static Complex add (Complex cvalue1,
Complex cvalue2) {
double r = cvalue1.real + cvalue2.real;
double i = cvalue1.imag + cvalue2.imag;
return new Complex (r, i);
}
 
Search WWH ::




Custom Search