What are wild card argument in Java?
Wildcard arguments in java means unknown type arguments. They act as placeholder for real arguments to be passed while calling the method. The arguments are denoted by question mark (?). One more important thing is that the types which are used to declare wildcard arguments must be generic types. Wildcard arguments are declared in three ways.
1) With An Unknown Type
2) With An Upper Bound
3) With Lower Bound
1) Wildcard Arguments With An Unknown Type :
The syntax for declaring this type of wildcard arguments is given below,
For example, Collection> or ArrayList> can hold any type of objects like String, Integer, Double etc.
2)Wildcard Arguments With An Upper Bound :
If you want the processElements() method to work with only numbers, then you can specify an upper bound for wildcard argument. To specify an upper bound for wildcards, use this syntax,
GenericType extends SuperClass>
This specifies that a argument can contain ‘SuperClass’ type or it’s sub classes. Remember that extends clause is an inclusive bound. i.e ‘SuperClass’ also lies in the bound.
3) Wildcard Arguments With Lower Bound :
You can specify a lower bound for wildcard argument using super clause. Here is the syntax,
GenericType super SubClass>
This means that a wildcard argument can contain ‘SubClass’ type or it’s super classes.
The question mark (?) is known as the wildcard in generic programming . It represents an unknown type. The wildcard can be used in a variety of situations such as the type of a parameter, field, or local variable; sometimes as a return type. Unlike arrays, different instantiations of a generic type are not compatible with each other, not even explicitly. This incompatibility may be softened by the wildcard if ? is used as an actual type parameter.
Upper Bounded Wildcards: These wildcards can be used when you want to relax the restrictions on a variable. For example, say you want to write a method that works on List < integer >, List < double >, and List < number > , you can do this using an upper bounded wildcard.
To declare an upper-bounded wildcard, use the wildcard character (‘?’), followed by the extends keyword, followed by its upper bound.
Lower Bounded Wildcards: It is expressed using the wildcard character (‘?’), followed by the super keyword, followed by its lower bound: super A>.
Unbounded Wildcard: This wildcard type is specified using the wildcard character (?), for example, List. This is called a list of unknown type.