Advanced Java Tutorial


Total available pages count: 55
Subject - Java Technologies

Wildcard in generics

The  “ ? “ represent the wildcard element. It means to any type. 

If you write  <? extends Number>, It means subclass of Number e.g., float, integer & double. You can call a method of number class through any sub-class of an object.

You can use a wildcard as type Parameter, return type, field, or local variable. It not allowed to use a wildcard as a type argument for generic method invocation. A generic supertype or instance creation.

Upper Bounded Wildcards

The Upper bounded wildcard used to decrease the restriction on a variable. It will put restrictions on an unknown type to be a subtype of that type. It is also used by declaring wildcard characters followed by extends or implements keywords.

List<? extends Number>

 

Where ,

  1. ?  = wildcard character
  2. extends = keyword
  3. Number = represent java.lang  package

Unbounded wildcard

Unbounded wildcard represents the list of an unknown type such as List<?>. 

Unbounded wildcard used:

  • When the given method is already implemented using functionality provided in an object class
  • When a generic class contains a method that does not depend on the type parameter.

Lower Bounded Wildcards

The main use of a lower bounded wildcard is used to restrict the unknown type to be supertype or a specific type of that type.

List<? super Integer>

 

Where,

  1. ? = wildcard character
  2. Super = keyword
  3. Integer =  wrapper class


Comments