**Due Date:** Monday, March 26, or Tuesday, March 27, 2007,
before the beginning of your lab section.

**Objective:** The main objective of this assignment is to learn
to design user-defined classes and ADTs.

**Programming assignment:** a complex number a + bi is
characterized by its real part a and its imaginary part b. For
complex numbers, the absolute value is defined as |a + bi| =
sqrt(a^2 + b^2), a conjugate is defined as (a + bi)' = a - bi.
Arithmetic operations are defined as follows:

(a + bi) - (c + di) = (a - c) + (b - d)i

(a + bi) * (c + di) = (a * c - b * d) + (a * d + b * c)i

(a + ib)/(c + id) = (ac + bd)/(c^2 + d^2) + i(bc - ad)/(c^2 + d^2) if c + id =/= 0.

Describe a class whose elements are complex numbers, and methods include:

- a constructor method,
- methods to return (accessor) and to change (mutator) the values of the parameters, and
- methods for the arithmetic operations.

Solution: public class Complex { //real part and imaginary part private double re; private double im; //constructor public Complex(double real, double imag) {re = real; im = imag;} //assessor methods public double getRe() {return re;} public double getIm() {return im;} //mutator methods public void setRe(double newRe) {re = newRe;} public void setIm(double newIm) {im = newIm;} //absolute value and conjugate public double absValue() {return Math.sqrt{re^2+im^2;} public Complex conjugate() {return new Complex(re,-im);} //arithmetic operations public Complex add(Complex secondNumber) { double newRe = re + secondNumber.getRe(); double newIm = im + secondNumber.getIm(); return new Complex(newRe, newIm); } public Complex subtract(Complex secondNumber) { double newRe = re - secondNumber.getRe(); double newIm = im - secondNumber.getIm(); return new Complex(newRe, newIm); } public Complex multiply(Complex secondNumber) { double newRe = re * secondNumber.getRe() - im * secondNumber.getIm(); double newIm = re * secondNumber.getIm() + im * secondNumber.getRe(); return new Complex(newRe, newIm); } public Complex divide(Complex secondNumber) { double secondRe = secondNumber.getRe(); double secondIm = secondNumber.getIm(); double denominator = secondRe * secondRe + secondIm * secondIm; double newRe = (re * secondRe + im * secondIm) / denominator; double newIm = (im * secondRe - re * secondIm) / denominator; return new Complex(newRe, newIm); } } public class Assignment8 { public static void main(String[] args) { Complex i = new Complex(0,1); Complex test = i.multiply(i); double real = test.getRe(); double imag = test.getIm(); System.out.printll("The square of i is equal to" + real + "+" + image + "i."); } }

**Deliverables:** as instructed by your TA.