-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQ1(Practical).java
More file actions
73 lines (68 loc) · 1.4 KB
/
Q1(Practical).java
File metadata and controls
73 lines (68 loc) · 1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
1) Design a class Complex having a real part (x) and an imaginary part (y). Provide methods
to perform the following on complex numbers:
a) Add two complex numbers.
b) Multiply two complex numbers.
c) toString() method to display complex numbers in the form: x + i y
public class Complex {
private int x;
private int y;
/**
* Parameterized Constructor of Complex class
*
* @param real Real Part
* @param imaginary Imaginary Part
*/
public Complex(int real, int imaginary) {
this.x = real;
this.y = imaginary;
}
/**
* Add two Complex Objects
*
* @param o Complex Object
* @return Complex Object
*/
public Complex add(Complex o) {
return new Complex(
this.x + o.x,
this.y + o.y
);
}
/**
* Multiply two Complex Objects
*
* @param o Complex Object
* @return Complex Object
*/
public Complex multiply(Complex o) {
return new Complex(
this.x * o.x - this.y * o.y,
this.x * o.y + o.x * this.y
);
}
/**
* Type Conversion to String
*
* @return String Representation
*/
@Override
public String toString() {
return x + " + i " + y;
}
}
/**** Main.java ****/
public class Main {
public static void main(String[] args) {
Complex c1 = new Complex(1, 2);
Complex c2 = new Complex(3, 4);
System.out.println("Complex 1: " + c1);
System.out.println("Complex 2: " + c2);
System.out.println("Sum: " + c1.add(c2));
System.out.println("Product: " + c1.multiply(c2));
}
}
Output
Complex 1: 1 + i 2
Complex 2: 3 + i 4
Sum: 4 + i 6
Product: -5 + i 10