1

I'm learning Java from the Oracle tutorials, and I've just reached Generics.

So we can use a bounded type parameter to restrict the types that can be used as type arguments. The tutorial brings the following method as an example:

class Box<T> {
...
 public <U extends Number> void inspect(U u){
        System.out.println("T: " + t.getClass().getName());
        System.out.println("U: " + u.getClass().getName());
    }
}

And I wonder - what is the benefit of using a bounded type parameter in a method? To be more precise, what is the benefit of the method above rather than:

public void inspect(Number u)

?

YoavKlein
  • 2,005
  • 9
  • 38
  • 2
    Does this answer your question? [What is PECS (Producer Extends Consumer Super)?](https://stackoverflow.com/questions/2723397/what-is-pecs-producer-extends-consumer-super) – Turing85 Jul 30 '23 at 12:19
  • 1
    IMO you are legitimately puzzled by this specific example, which most probably offers no benefit, as mentioned in the comment above. It would be useful to express e.g. a constraint that `inspect` takes 2 arguments, they are both subclasses of `Number` but **must be of the same type**. In this case `inspect(Number x, Number y)` would allow you to pass `(Long, Double)`, which does not capture the constraint. Defining it as ` void inspect(U x, U y)` does. This is another usage, in addition to the PECS from a previous comment. – Nikos Paraskevopoulos Jul 30 '23 at 12:30
  • 1
    Purpose of above example is to show *how* to use generic methods, not *when* to use them. – Pshemo Jul 30 '23 at 12:31
  • The point of type variables on generic methods is to link things together - say, a parameter and return type, or two parameters (but only when at least one is generic): you can also use them to express generic bounds on parameters like `U extends Comparable super U>>`. In your example, there is no point in using a type variable. – Andy Turner Jul 30 '23 at 19:34

0 Answers0