0

I'm new to Java & have learned Generics Today. Im facing this problem & I don't know what I did wrong here!! I really appreciate any help you can provide:)

//Practice Que:  
//AIM of this code:: to pass any "Number" type(byte, int, float...) and get its sum,sub,mul

class Operations<T extends Number> {
    T x1, x2;

    public Operations(T x1, T x2) {
        super();
        this.x1 = x1;
        this.x2 = x2;
    }

    public void Arithmetic() {
        // ----- **WHY ERROR???** => The operator +,-,* is undefined for the argument type(s) T, T ------------
        System.out.println("sum: " + (x1 + x2));
        System.out.println("sub: " + (x1 - x2));
        System.out.println("mul: " + x1 * x2);
        // ----------------------------------------------------------------------------------------
    }
}

public class Example1 {
    public static void main(String[] args) {
        // for Integer
        Operations<Integer> o1 = new Operations<>(2, 3);
        o1.Arithmetic();

        // for Float
        Operations<Float> o2 = new Operations<>(2.5f, 3.5f);
        o2.Arithmetic();
    }
}
  • Because +, - and * are not defined for arbitrary Number types. – akarnokd Jun 19 '22 at 11:22
  • 1
    Why do you expect that an instance of `Number`, which is a supertype of `BigDecimal`, `AtomicInteger`, etc., can be converted into a primitive? FYI, arithmetic operators (`+`, `-`, etc.) can be use **only** with primiteves. – Alexander Ivanchenko Jun 19 '22 at 11:23
  • @akarnokd got your point thank you – Abhijeet Take Jun 19 '22 at 11:29
  • @AlexanderIvanchenko thank you... now I understood where I did a mistake. so How can I convert it into primitive? is it possible? { my intention here was to pass int, double, float...etc type of data and get their respective result} – Abhijeet Take Jun 19 '22 at 11:32
  • @AlexanderIvanchenko Thank you for providing the link. my doubt is resolved :) – Abhijeet Take Jun 19 '22 at 11:41
  • It can't be done automatically without type casting. And there's no way to achieve that using bounded generic type because after `exstends` you can provide only **one** class. – Alexander Ivanchenko Jun 19 '22 at 11:41

0 Answers0