কমপ্লেক্স নম্বর duটি অংশে ভাগ: রিয়েল (Real) এবং ইম্যাজিনারি (Imaginary)। জাভায় বিল্ট-ইন কমপ্লেক্স টাইপ নেই, তাই কাস্টম ক্লাস বানাতে হয়।
উদাহরণ: যোগফল
class Complex {
double real, imag;
Complex(double real, double imag) {
this.real = real;
this.imag = imag;
}
static Complex add(Complex a, Complex b) {
return new Complex(a.real + b.real, a.imag + b.imag);
}
@Override
public String toString() {
return real + " + " + imag + "i";
}
}
public class Main {
public static void main(String[] args) {
Complex c1 = new Complex(76.8, 24.0);
Complex c2 = new Complex(65.9, 11.23);
Complex sum = Complex.add(c1, c2);
System.out.println("যোগফল: " + sum); // 142.7 + 35.23i
}
}
বিয়োগ, গুন, ভাগও একইভাবে ইমপ্লিমেন্ট করা যায়।