Generic methods and Wildcard character

//Generic methods and Wildcard character
  1. Generic Methods

  2. Wild Cards (?)

  3. Upper bounded wildcards

  4. Unbounded wildcards

  5. Lower bounded wildcards

 

Generic Methods :

  1. Generic methods are methods that introduce their own type parameters. This is similar to declaring a generic type at class level, but the type parameter’s scope is limited to the method where it is declared.
  2. Static and non-static generic methods are allowed, as well as generic class constructors.
  3. Syntax : The syntax for a generic method includes a type parameter, inside angle brackets, and appears before the method’s return type. For static generic methods, the type parameter section must appear before the method’s return type.

  1. In generic code, the question mark (?), called the wildcard, represents an unknown type. The wildcard can be used in a variety of situations: as the type of a parameter, field, or local variable; sometimes as a return type.

Types are:

  1. Upper bounded wildcards.
  2. Unbounded wildcards.
  3. Lower bounded wildcards.

1. Upper bounded wildcards

To declare an upper-bounded wildcard, use the wildcard character (‘?‘), followed by the extends keyword, followed by its upper bound:<? extends A>.

  1.  X can be a class or interface.
  2. If X is a class then as a type parameter we can use either X type or its child classes.
  3. If X is interface then as a type parameter we can use either X type or its implementation class Type.
  4. In this case we are allow to add we are not allow to add anything except null with in the method.

2. Unbounded wildcards

The unbounded wildcard type is specified using the wildcard character (?), for example, List<?>.

This method is applicable for ArrayList of any type but with in the method we are not allow to add anything except null.

3. Lower bounded wildcards

A lower bounded wildcard is expressed using the wildcard character (‘?‘), following by the super keyword, followed by its lower bound: <? super A>.

  1. X can be a class or interface.
  2. If X is a class then as a type parameter we can use either X type or its super (parent) classes.
  3. If X is interface then as a type parameter we can use either X type or its super classes of its implementation class Type X (but not for implementation classes).
  4. In this case we are allow to add ‘X’ type objects and null with in the method.

Leave A Comment