0% completed
Generic classes allow you to write classes that can operate on objects of various types while providing compile-time type safety. Instead of specifying a concrete type, a generic class uses type parameters as placeholders. This makes your code more flexible and reusable. Generic classes are widely used in the Java Collections Framework and other parts of the language.
public class ClassName<T> { // Field of generic type private T value; // Constructor to initialize the generic field public ClassName(T value) { this.value = value; } // Getter method for the generic field public T getValue() { return value; } // Setter method for the generic field public void setValue(T value) { this.value = value; } }
ClassName<T>
declares a generic class with a type parameter T
.value
is of type T
and can hold any object of the type specified when an instance is created.Box<Integer> intBox = new Box<>(123);
Integer
is referred as a generic type and "123" is a value passed as an argument.This example demonstrates a generic class called Box
that can store an object of any type. We then create instances of Box
for different types (e.g., Integer
and String
) and use the getter method to display the stored values.
Example Explanation
Generic Class Definition:
Box<T>
class is defined with a type parameter T
.content
of type T
and provides getter and setter methods.Creating Instances:
Box<Integer>
is created to store an integer value (123
).Box<String>
is created to store a string ("Hello Generics!"
).Output:
getContent()
method retrieves and prints the stored values, demonstrating type safety and reusability.This example illustrates a generic class named Pair
that accepts two type parameters, K
and V
, to store a key-value pair. We create an instance of Pair
and print both the key and the value.
Example Explanation:
Pair<K, V>
class uses two type parameters to store a key and a value.Pair<String, Integer>
instance is created with key "Age"
and value 30
.Generic classes in Java allow you to create flexible, reusable, and type-safe classes that work with various data types. By parameterizing types with placeholders (like T
, K
, V
), you can write code that is independent of any specific type and catch type errors at compile time. These techniques are foundational for building robust and reusable components in Java applications.
.....
.....
.....