What is Generics in Java?
Generics is a way of implementing generic programming. Generic programming provides the facility like for a set of related methods, declare a single method that support any valid types. Generics are introduced in java 5. In java, generics are added because of Compile time type safety.
See more at: Generics in java.
How generics work?
Generics work on the concept of “Type Erasure”. As we discussed above generics are used for compile time type safety i.e. they work at the compile time. At the compile time java compiler uses the Type Erasure feature to erase or remove the generics type code and convert the code without generics.
See more at: How generics work?
What is Bounded and Unbounded wildcards in Generics?
Wildcard:
In generics ‘?’ is known as wildcard and it represents an unknown type.
Types of wildcard:
- 1. Unbounded wildcard.
- 2. Bounded wildcard.
1. Unbounded wildcard.is used for list of unknown types using ‘?’(Type is not bounded).
2. Bounded wildcard: is used for unknown bounded types using ‘?’ with extends or super keyword.
- a. Upper bounded wildcard. is used to restrict the unknown type to be a specific type or a subtype of that type using ‘?’ with extends keyword.
- b. Lower bounded wildcard. is used to restrict the unknown type to be a specific type or a super type of that type using ‘?’ with super keyword.
See more at: Wildcard in generics.
Explain Generic classes/interfaces.
Generic classes/interfaces have the class name followed by a type parameter section. Type parameter section of can have one or more type parameters separated by commas. These classes/interfaces are known as parameterized classes/interfaces.
See more at: Generic classes/interfaces.
Explain Generics method in java.
The methods which can handle different types of arguments are known as generic methods. Types of the argument are specified on method call.
See more at: Generics methods.
Explain Generics constructor in java.
A constructor can be declared as generic, independently of whether the class that the constructor is declared in is itself generic. A constructor is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the constructor. The form of the formal type parameter list is identical to a type parameter list of a generic class or interface. The interface constructor is generic.
See more at: Generics constructor.