Object Oriented Programming Lab
Assignment: 5
Create a class named complex with data members as real and imaginary. Overload three
constructors to initialize the data members (i.e. default, normal/parameterized and through
object initialization). Provide methods which returns object of the complex class as the
result for addition, subtraction, multiplication of two complex numbers.
CODE:
import java.io.*;
class Complex{
double real,img;
Complex(){
real=2.2;
img=5.0;
}
Complex(double tempreal,double tempimg){
real=tempreal;
img=tempimg;
}
Complex(Complex obj1){
real=obj1.real;
img=obj1.img;
}
Complex add(Complex C1,Complex C2){
Complex ans=new Complex();
ans.real=C1.real+C2.real;
ans.img=C1.img+C2.img;
return ans;
}
Complex sub(Complex C1,Complex C2){
Complex ans=new Complex();
ans.real=C1.real-C2.real;
ans.img=C1.img-C2.img;
return ans;
}
Complex mul(Complex C1,Complex C2){
Complex ans=new Complex();
ans.real=C1.real*C2.real;
ans.img=C1.img*C2.img;
return ans;
}
void print(){
System.out.println("Complex Number is :" +real +"+"+img+"i");
}
public static void main(String[] args) throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Your Choice:");
int ch=Integer.parseInt(br.readLine());
switch(ch){
case 1:
Complex d1=new Complex();
Complex d2=new Complex();
Complex d3=new Complex();
d3=d3.add(d1,d2);
d3.print();
d3=d3.sub(d1,d2);
d3.print();
d3=d3.mul(d1,d2);
d3.print();
break;
case 2:
System.out.println("Enter the first complex number:");
double r1=Double.parseDouble(br.readLine());
double i1=Double.parseDouble(br.readLine());
System.out.println("Enter the second complex number:");
double r2=Double.parseDouble(br.readLine());
double i2=Double.parseDouble(br.readLine());
Complex C3=new Complex(r1,i1);
Complex C4=new Complex(r2,i2);
Complex C5 =new Complex();
C5=C5.add(C3,C4);
System.out.println("After Addition:");
C5.print();
C5=C5.sub(C3,C4);
System.out.println("After Subraction:");
C5.print();
C5=C5.mul(C3,C4);
System.out.println("After Muliplication:");
C5.print();
break;
case 3:
System.out.println("Enter the first complex number:");
double real1=Double.parseDouble(br.readLine());
double img1=Double.parseDouble(br.readLine());
System.out.println("Enter the second complex number:");
double real2=Double.parseDouble(br.readLine());
double img2=Double.parseDouble(br.readLine());
Complex C6=new Complex(real1,img1);
Complex C7=new Complex(real2,img2);
Complex C8=new Complex(C6);
Complex C9=new Complex(C7);
Complex C10=new Complex();
System.out.println("After Addition:");
C10=C10.add(C6,C7);
C10.print();
System.out.println("After Subraction:");
C10=C10.sub(C6,C7);
C10.print();
System.out.println("After Muliplication:");
C10=C10.mul(C6,C7);
C10.print();
break;
}
}
}
OUTPUT: