Java Programming Practical 7

Question 1
Write a program to implement different types of constructors to perform addition of complex numbers.
ComplexDemo.java
Java
				class Complex 
{
    float real;
    float img;

    public Complex() 
	{
        real = 0.0f;
        img = 0.0f;
    }

    public Complex(float r) 
	{
        real = r;
        img = 0.0f;
    }

    public Complex(float r, float i) 
	{
        real = r;
        img = i;
    }

    public void add(Complex other) 
	{
        real=real+other.real;
		img=img+other.img;
		System.out.println("Addition is :"+real+" + "+img+"i");
    }
}

public class ComplexDemo
{
    public static void main(String[] args) 
	{
        Complex num1 = new Complex(); 
        Complex num2 = new Complex(5.0f); 
        Complex num3 = new Complex(2.0f, 3.0f); 
        Complex num4 = new Complex(1.0f, 2.0f);

        num1.add(num2);
        num3.add(num4);
    }
}
			
Output

Leave a Comment

Your email address will not be published. Required fields are marked *