Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics Class<? extends Number> explanation

Tags:

java

generics

public void foo(Class<? extends Number> value) {
    // compilation error
    processNumber(value);
}

public void processNumber(Number num) {
    // do something about this number.
}

I would like to call "foo" from any subtype of Number (Integer, Double ..etc) Can anyone explain to me how should I do it ?

foo(new Integer(5)); // compilation error 
like image 955
karephul Avatar asked Jun 29 '26 04:06

karephul


1 Answers

You are passing a Class object as a value but processNumber takes a Number.

You can use this signature:

public void foo(Number value)

to be able to pass any kind of Number into foo but keep in mind the Liskov Substitution Principle.

As a side note: you don't need foo(new Integer(5)); you can do this instead: foo(5);

like image 143
Adam Arold Avatar answered Jul 01 '26 17:07

Adam Arold



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!