![]() |
VOOZH | about |
In Java, Generics are the parameterized types that allow us to create classes, interfaces, and methods in which the type of data they are dealing with will be specified as a parameter. This ensures the type safety at the compilation time.
class class_name<T>
{
//Body of the class
}
Here, the T is a type parameter that can be replaced with any valid identifier. Similarly, generic methods and interfaces are also created.
There are a few restrictions associated with the usage of generics that are mentioned below:
It is not possible to create an instance of a type parameter. The compiler doesn't know what type of object to create, their T is simply a placeholder. Below is the example code that shows the invalid creation of an instance of T which leads to a compilation error.
Example:
10
It is illegal for the static members(variables, methods) to use a type parameter declared by the enclosing class. We will use the above example in this case to make the variable and method static, this also leads to compile time error. Let's see in detail what the compiler says:
Example:
Geek For Geeks!!
There are two important generic restrictions that applied to arrays.
Example:
value: 10 [1, 2, 3, 4, 5]
We will get the compilation error if we use the primitive data types at the time of object creation. The following code demonstrates the situation:
Example:
value: 10 value: Geek For Geeks
We cannot create generic exception classes and cannot extend throwable (which is superior to all exception classes in the exception class hierarchy). We will use the above example to understand this, although we get an error if we execute this code, give it a try.
Example:
Output:
Error: Could not find or load main class Box Caused by: java.lang.ClassNotFoundException: Box