public class ComplexNumber { public static void main(String args[]) { System.out.println("\nComplexNumber.main()"); Complex c1 = new Complex(1, 2), // instantiate Complex numbers c2 = new Complex(2, 1); Number n1 = new Number(3), // instantiate ordinary numbers n2 = new Number(4); System.out.println(c1.plus(c2)); // apply plus to c1, giving it c2 // plus returns a new Complex number, which has a toString() System.out.println(c1.minus(c2)); System.out.println(c1.times(c2)); System.out.println(n1.plus(n2)); // similar for ordinary numbers System.out.println(n1.minus(n2)); System.out.println(n1.times(n2)); } } class Complex { private double re, im; // Complex numbers have two parts public Complex(double re, double im) { // constructor receives and stores the two parts this.re = re; this.im = im; } public double real() { // accessor methods return re; } public double imag() { return im; } public Complex plus(Complex c) { // return a new Complex number based on the two parts // of "this" object, and the two parts of the parameter c. return new Complex(re + c.real(), im + c.imag()); } public Complex minus(Complex c) { return new Complex(re - c.real(), im - c.imag()); } public Complex times(Complex c) { return new Complex(re*c.real() - im*c.imag(), re*c.imag() + im*c.real()); } public String toString() { // makes for easy printing of Complex numbers if (re!=0 && im>0) return re +" + " + im + "i"; if (re!=0 && im<0) return re + " - " + (-im) + "i"; if (im==0) return String.valueOf(re); // static call if (re==0) return im + "i"; return "Unknown"; } } class Number extends Complex { // derived class, or subclass public Number(double n) { // constructor only needs one number super(n,0.0); // call parent's constructor with a default imaginary value } }