![]() |
VOOZH | about |
In Java, Generics provide type-safe, reusable code by allowing parameterized types. They enable classes, interfaces and methods to work with any data type (e.g., Integer, String or custom types) while ensuring compile-time type checking and reducing runtime errors. Using type parameters like <T>, generics promote cleaner, more flexible and stable code.
A generic class can be reused with any data type by replacing T with specific types like Integer, String or custom classes. It is declared like a regular class but includes a type parameter (e.g., <T>) after the class name.
You can define multiple type parameters in a generic class using commas (e.g., <K, V>).
A generic method is a method that declares its own type parameters. It can be called with arguments of different types and the compiler infers the correct type during the method call.
Rules for Generic Methods
1. Type-Safety: One can hold only a single type of objects in generics.
2. Type Casting Is Not Required: There is no need to typecast.
Example:
3. Compile -Time Checking: It checks all the errors of datatype related to generics at the time of compile-time so the issue will not occurat the time of runtime.
List<String> list = new ArrayList<String>();
list.add("hello");
list.add(32); //Compile Time Error
For an example of Generic class
BaseType <Type> object = new BaseType <Type>();
Note: In parameter Type, we cannot use primitives like int, char, float, etc.
Example:
10 2.5