Generic classes in Java provide a powerful way to create flexible, type-safe code that works with different data types. They allow you to write classes that can operate on objects of various types while maintaining compile-time type safety.
Generic classes are classes that are parameterized over types. They enable you to define a class with a placeholder for the type of data it can work with. This placeholder is called a type parameter.
To create a generic class, use angle brackets <>
after the class name and specify one or more type parameters. Here's the basic syntax:
public class ClassName<T> {
// Class body
}
In this syntax, T
is a type parameter that can be replaced with any valid Java type when the class is instantiated.
Let's create a simple generic class that can hold any type of object:
public class Box<T> {
private T content;
public void set(T content) {
this.content = content;
}
public T get() {
return content;
}
}
Now you can use this Box
class with different types:
Box<Integer> intBox = new Box<>();
intBox.set(10);
int value = intBox.get();
Box<String> stringBox = new Box<>();
stringBox.set("Hello, Generics!");
String message = stringBox.get();
Generic classes can have multiple type parameters. This is useful when you need to work with more than one type in your class:
public class Pair<K, V> {
private K key;
private V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() { return key; }
public V getValue() { return value; }
}
You can restrict the types that can be used with your generic class by using bounds. For example, to create a class that works only with numbers:
public class NumberBox<T extends Number> {
private T number;
public void set(T number) {
this.number = number;
}
public double getDoubleValue() {
return number.doubleValue();
}
}
This NumberBox
class can only be used with types that extend Number
, such as Integer
, Double
, or Float
.
T
for type, E
for element, K
for key, V
for value)<>
for brevity when instantiating generic classes in Java 7 and laterTo deepen your understanding of generics in Java, explore these related topics:
Generic classes are a fundamental part of Java's type system, enabling developers to write more flexible and robust code. By mastering generic classes, you'll be able to create reusable components that work seamlessly with various data types while maintaining type safety.