Ah! My old assignment.
Code:
/* Note: Class not defined public to stuff all the code in one source file. */
/* Complex class */
class Complex {
private double a; // Real part of the complex number
private double b; // Imaginary part of the complex number
/* Constructors */
public Complex() {
// Default no-arg constructor.
// Real and imaginary parts are 0.0d by default.
}
public Complex(double real, double imaginary) {
// Set the real and imaginary parts
this.a = real;
this.b = imaginary;
}
public Complex(Complex complex) {
// Create a copy of the Complex object passed as argument.
this.a = complex.getReal();
this.b = complex.getImaginary();
}
/* Overloaded toString() method from java.lang.Object
to print the Complex number representation. */
public String toString() {
return this.a +(this.b>0?"+":"") +this.b +"j";
}
/* Getter methods */
public double getReal() { return this.a; }
public double getImaginary() { return this.b; }
/* Setter methods */
public void setReal(double real) {
this.a = real;
}
public void setImaginary(double imaginary) {
this.b = imaginary;
}
/* Returns the absolute value */
public double abs() {
// This method will work with JDK 1.5
return Math.hypot(this.a, this.b);
/*
For older versions of JDK, use the following line instead:
Math.sqrt(Math.pow(this.a, 2) +Math.pow(this.b, 2));
*/
}
/* Square of absolute value */
public double sqAbs() {
return Math.pow(this.a, 2) +Math.pow(this.b, 2);
}
/* Complex Conjugate of the complex number */
public Complex conjugate() {
// Returns a-b*j
return new Complex(this.a, -this.b);
}
/* Reciprocal of the Complex number */
public Complex reciprocal() {
// Returns (a-b*j)/(a^2 +b^2)
Complex reciprocal = this.conjugate();
double sqAbs = this.sqAbs();
reciprocal.setReal(reciprocal.getReal()/sqAbs);
reciprocal.setImaginary(reciprocal.getImaginary()/sqAbs);
return reciprocal;
}
/* TODO: Add other methods for complex number operations here. */
}
/* Class to test the Complex number operations. */
public class TestComplex {
public static void main(String[] argv) {
Complex complex = new Complex(1, 2);
System.out.println("Complex number = " +complex);
System.out.println("Absolute value = " +complex.abs());
System.out.println("Reciprocal = " +complex.reciprocal());
}
}
Here's how it could be done. Basically, you need to create a complex class which will hold the real and imaginary parts as private member variables. The interface would be provided through public methods, each representing some operation on the complex number. Any method which needs to perform mathematical operations on the complex number would be using the methods to perform the arithmetic.
I have added some comments in my code. See if this explains satisfactorily.
Bookmarks