In Java, bounded types are generic types that are defined with one or more type parameters that are bounded by other types. Bounded types are used to specify constraints on the types that can be used as arguments for the type parameter.
Here is an example of a bounded type in Java:
public class Box<T extends Comparable<T>> { private T value; public Box(T value) { this.value = value; } public T getValue() { return value; } public void setValue(T value) { this.value = value; } }Source:www.lautturi.com
In this example, the Box
class is a bounded type that has a type parameter T
that is bounded by the Comparable
interface. This means that the T
type parameter can only be replaced with a type that implements the Comparable
interface.
To use the Box
class, you can specify the type argument for T
when you create an instance of the class. For example:
Box<Integer> box = new Box<>(10); System.out.println(box.getValue()); // prints 10 Box<String> box2 = new Box<>("Hello"); System.out.println(box2.getValue()); // prints Hello
In the first example, the Box
class is parameterized with the Integer
type, which is a concrete class that implements the Comparable
interface. In the second example, the Box
class is parameterized with the String
type, which also implements the Comparable
interface.
Bounded types are useful when you want to specify constraints on the types that can be used as arguments for a generic type. This can help to ensure type safety and prevent runtime errors in your code.