generic class
generic class
GENERICS
In
Advance Java
Definition of
GENERICS IN JAVA
Generics
@pravanjan_17p
GENERICS
KEY CONCEPTS
OF GENERICS
1. TYPE SAFETY
2. CODE REUSABILITY
@PRAVANJAN_17P
HOW GENERICS WORK
1. Generic Classes
A generic class allows you to define classes that
work with any data type.
Pravanjan.txt
class Box<T> {
private T item;
public void setItem(T item) {
this.item = item; }
public T getItem() {
return item; } }
public class Main {
public static void main(String[] args) {
Box<String> stringBox = new Box<>();
stringBox.setItem("Hello");
System.out.println(stringBox.getItem());
Box<Integer> intBox = new Box<>();
intBox.setItem(123);
System.out.println(intBox.getItem());
}
}
@pravanjan_17p
HOW GENERICS WORK
2. Generic Methods
A generic method allows you to declare a
method with type parameters.
Pravanjan.txt
class Util {
public static <T> void printArray(T[] array) {
for (T element : array) {
System.out.println(element);
}
}
}
@pravanjan_17p
HOW GENERICS WORK
class MathUtils {
public static <T extends Number> double square(T
number) {
return number.doubleValue() *
number.doubleValue();
}
}
@pravanjan_17p
GENERICS AND COLLECTIONS
Pravanjan.txt
import java.util.ArrayList;
@pravanjan_17p
GENERICS AND COLLECTIONS
Pravanjan.txt
import java.util.HashMap;
@pravanjan_17p
JAVA
Advantages of Generics
1 - Type Safety:
Prevents runtime errors by catching type
mismatches at compile time
2 - Code Reusability:
Allows writing generic code that works
with any data type.
3 - Performance:
Eliminates the need for typecasting,
reducing runtime overhead.
@pravanjan_17p
JAVA
Limitations of Generics
1 - Type Erasure:
Generics are implemented using type erasure,
so the type parameter is removed at runtime.
3 - No Static Members:
Generic classes cannot have static members
with type parameters.
@pravanjan_17p
Did you like it?
follow for more!
@pravanjan_17p