Java Interview Questions

BY Author

Java – Generics with WildCard Arguments

In the game of cards, the wild card can replace any other card or can be matched with any other card to form a pair.

For example, generally, we consider Jokercard as a wild card. Therefore it can replace any other card or can be matched with any card to form a pair.

Similarly, in Java, generics use a concept known as a wildcardwhich can match with any reference type among valid types.

It is denoted by the sign ‘?’.

Why wildcard?

To understand where and why wildcardmust be used in Generics, let’s take a small example.Consider a generic class WCDemowhich uses bounded type parameter that extends TenWheeler. Therefore it can be used with TenWheeler& its subclasses Bus& Truck.Suppose we want to pass the Trucktype to the check() method invoked by Bustype.Then you might think it a very simple task & write a program as shown below: