Program of Complex Number using OOP

class ComplexNumber {
    private double real;
    private double img;

    ComplexNumber() {
        real = img = 0.0;   
    }

    ComplexNumber(double real, double img) {
        this.real = real;
        this.img = img;   
    }

    public ComplexNumber add(ComplexNumber c2) {
        return new ComplexNumber(this.real + c2.real, this.img + c2.img);    
    }

    public ComplexNumber multiply(ComplexNumber c2) {
        return new ComplexNumber(this.real * c2.real - this.img * c2.img, this.real * c2.img + this.img * c2.real);
    }

    public String toString() {
        return (img < 0) ? (real + " - " + Math.abs(img) + "i") : (real + " + " + img + "i");   
    }
}

public class ComplexNumberOperations {
    public static void main(String[] args) {
        ComplexNumber c1 = new ComplexNumber(1.0, -2.0);
        ComplexNumber c2 = new ComplexNumber(3.0, 4.0);


        System.out.println(c1.add(c2));
        System.out.println(c1.multiply(c2));
    }
}

Comments

Popular posts from this blog

Zeller's Congruence

Property Event-Delegation

Method with variable arguments