generic class
generic class
Java Generics was introduced to deal with type-safe objects. It
makes the code stable. Java Generics methods and classes, enables
programmer with a single method declaration, a set of related
methods, a set of related types. Generics also provide compile-
time type safety which allows programmers to catch invalid types
at compile time. Generic means parameterized types. Using
generics, the idea is to allow any data type to be it Integer,
String, or any user-defined Datatype and it is possible to create
classes that work with different data types.
A Generic class simply means that the items or functions in that
class can be generalized with the parameter(example T) to specify
that we can add any type as a parameter in place of T like Integer,
Character, String, Double or any other user-defined type.
Example: Single type parameter
class Solution<T>
{
T data;
public static T getData(){
return data;
}
}
private K key;
private V value;
Here in this example, we can use the object or instance of this class
as many times with different Parameters as T type. If we want the
data to be of int type, the T can be replaced with Integer, and
similarly for String, Character, Float, or any user-defined type. The
declaration of a generic class is almost the same as that of a non-
generic class except the class name is followed by a type parameter
section. The type parameter section of a generic class can have one
or more type parameters separated by commas.
We can write a single generic method declaration that can be called
with arguments of different types. Based on the types of arguments
passed to the generic method, the compiler handles each method
call appropriately. Following are the rules to define Generic
Methods
All generic method declarations have a type parameter
section indicated by angle brackets <> that precedes the
method’s return type.
Each type parameter section can contain one or more
type parameters separated by commas. A type
parameter or a type variable is an identifier that specifies a
generic type name.
The type parameters can be used to declare the return type
which is known as actual type arguments.
A generic method’s body is declared like that of any non-
generic method. The point to be noted is that type
parameter can represent only reference types, and not
primitive types (like int, double, and char).
Advantages of Java Generics
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:
Before Generics
List l= new ArrayList();
l.add("India");
String s = (String) l.get(0); // typecasting
// Generic Classes
Output
10
2.5