Generic Types in Java¶
Generic Types in Java are a feature that allows developers to specify and work with types (classes and interfaces) as parameters.^[600-developer__java__java-base__Generics.md]
Categories of Generics¶
Generics in Java are primarily categorized into three forms:^[600-developer__java__java-base__Generics.md]
- Generic Classes
- Generic Interfaces
- Generic Methods
Generic Methods¶
A Generic Method introduces its own type parameters, independent of the generic types defined by the class in which it resides.^[600-developer__java__java-base__Generics.md] This allows the method to vary independently of the class, enabling more flexible and type-safe operations.
Bounded Type Parameters¶
Generic methods can restrict the types they accept using bounded type parameters.^[600-developer__java__java-base__Generics.md] For instance, a method may specify that a type parameter must extend a specific class, such as Number.
Code Example¶
The following example demonstrates a generic class Generic with a type parameter T, alongside a generic method showKeyName that uses a distinct type parameter U bounded by Number:^[600-developer__java__java-base__Generics.md]
class Generic<T> {
T key;
public T getKey() {
return key;
}
public <U extends Number> U showKeyName(Generic<U> [container](<./container.md>)) {
System.out.println("[container](<./container.md>) key :" + [container](<./container.md>).getKey());
U test = [container](<./container.md>).getKey();
return test;
}
}
Related Concepts¶
- Java
- [[Type Parameters]]
- [[Bounded Types]]
Sources¶
600-developer__java__java-base__Generics.md