0% found this document useful (0 votes)
7 views2 pages

Practical 7

The document contains a Java class definition for a Complex number, including constructors, an addition method, and a display method. The main class demonstrates creating Complex objects, adding them, and displaying the results. It also shows how to create a copy of a Complex object.

Uploaded by

banuarjuman747
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views2 pages

Practical 7

The document contains a Java class definition for a Complex number, including constructors, an addition method, and a display method. The main class demonstrates creating Complex objects, adding them, and displaying the results. It also shows how to create a copy of a Complex object.

Uploaded by

banuarjuman747
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Pr-7

class Complex {
double real, imaginary;

public Complex() {
real = 0;
imaginary = 0;
}

public Complex(double real, double imaginary) {


this.real = real;
this.imaginary = imaginary;
}

public Complex(Complex other) {


this.real = other.real;
this.imaginary = other.imaginary;
}

public Complex add(Complex other) {


double realSum = this.real + other.real;
double imaginarySum = this.imaginary + other.imaginary;
return new Complex(realSum, imaginarySum);
}

public void display() {


if (imaginary >= 0)
System.out.println(real + " + " + imaginary + "i");
else
System.out.println(real + " - " + (-imaginary) + "i");
}
}

public class Main {


public static void main(String[] args) {

Complex c1 = new Complex();


Complex c2 = new Complex(4.5, 3.2);

System.out.print("Complex number c1: ");


c1.display(); pr-7

System.out.print("Complex number c2: ");


c2.display();

Complex c3 = c1.add(c2);

System.out.print("Sum of c1 and c2: ");


c3.display();

Complex c4 = new Complex(c3);


System.out.print("Copy of c3 (c4): ");
c4.display();
}
}

You might also like