Generic Class with Type Bounds

Implements a generic Box class with type bounds, demonstrating how generics provide compile-time type safety while working with constrained type parameters.

JavaData Integrity

Code

snippet
public class GenericClass {

    static 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;
        }

        public boolean isGreaterThan(Box<T> other) {
            return this.value.compareTo(other.value) > 0;
        }
    }

    static class Pair<K, V> {
        private final K key;
        private final V value;

        public Pair(K key, V value) {
            this.key = key;
            this.value = value;
        }

        public K getKey() { return key; }
        public V getValue() { return value; }

        @Override
        public String toString() {
            return key + "=" + value;
        }
    }

    public static void main(String[] args) {
        Box<Integer> intBox = new Box<>(42);
        Box<Integer> otherBox = new Box<>(10);
        System.out.println("42 > 10: " + intBox.isGreaterThan(otherBox));

        Pair<String, Integer> pair = new Pair<>("age", 30);
        System.out.println("Pair: " + pair);
    }
}