How do you use generic type bounds with a simple code example?

In Java, generic type bounds allow you to specify constraints on the types that can be used as type arguments in generics. This can help in ensuring type safety and providing additional functionality based on the types used. Below is a simple example that demonstrates the usage of generic type bounds.

// Generic class with type bounds public class Box { private T item; public Box(T item) { this.item = item; } public double getDoubleValue() { return item.doubleValue(); } public void setItem(T item) { this.item = item; } public T getItem() { return item; } } public class Main { public static void main(String[] args) { Box intBox = new Box<>(10); System.out.println("Integer Value: " + intBox.getDoubleValue()); Box doubleBox = new Box<>(10.5); System.out.println("Double Value: " + doubleBox.getDoubleValue()); } }

Generic Type Bounds Java Generics Type Safety Java Programming