0

I'm new to Java. The Following Code is to create a generic class to generate complex numbers from real and Imaginary Parts. The add() method in the class is throwing the following Error. Not sure how to proceed further. I have been at this for a day. Error Prompt

import java.util.*;


  class ComplexNum<T>{
    
    T i;
    T r;
    
    public ComplexNum (T r , T i){
        
        this.r = r;
        this.i = i;
    }
    
    public ComplexNum add(ComplexNum c2)
    {
       
        
        return new ComplexNum (r + c2.r, i +c2.i);

    }
    
    
    @Override
    public String toString() {
        return this.r + " + " + this.i + "i";
    }
    
}



class Main{
public static void main(String[] args) {
        int n1 = 1;
        int n2 = 3;
        double d1 =4.4;
        double d2 = 5.4;
       
        ComplexNum<Integer> c1 = new ComplexNum<Integer>(n1, n2);
        ComplexNum<Double> c2 = new ComplexNum<Double>(d1, d2);
       ComplexNum<Double> c3 = c1.add(c2);
       System.out.println(c1 + " + " + c2 + " = "+ c3) ;
       
       
    }
}
  • 1
    Please don't post images of text. – tgdavies Jun 12 '22 at 11:16
  • 2
    `T` can be any type. Not every type has addition defined on it. – tgdavies Jun 12 '22 at 11:20
  • 1
    Does this answer your question? [Can I do arithmetic operations on the Number baseclass?](https://stackoverflow.com/questions/3873215/can-i-do-arithmetic-operations-on-the-number-baseclass) – Joe Jun 12 '22 at 11:26

1 Answers1

0
static class ComplexNum<T extends Number> {

    T i;
    T r;

    public ComplexNum(T r, T i) {

        this.r = r;
        this.i = i;
    }

    public ComplexNum<Double> add(ComplexNum c2) {
        Double newr = r.doubleValue() + c2.r.doubleValue();
        Double newi = i.doubleValue() + c2.i.doubleValue();

        return new ComplexNum<>(newr, newi);

    }


    @Override
    public String toString() {
        return this.r + " + " + this.i + "i";
    }

}


class Main {
    public static void main(String[] args) {
        int n1 = 1;
        int n2 = 3;
        double d1 = 4.4;
        double d2 = 5.4;

        ComplexNum<Integer> c1 = new ComplexNum<>(n1, n2);
        ComplexNum<Double> c2 = new ComplexNum<>(d1, d2);
        ComplexNum<Double> c3 = c1.add(c2);
        System.out.println(c1 + " + " + c2 + " = " + c3);


    }
}