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

How the snippet works

All of the logic lives in the classes GenericClass, Box and Pair and the functions Box, getValue, setValue and isGreaterThan.

Applying it

The signature you will reach for first is public Box(T value)

The demo output is labeled (42 > 10:, Pair:), so the printed output reads as a trace of the operations performed.

The sequence isGreaterThan lives in main; running the file triggers it.

Statements that matter

return this.value.compareTo(other.value) > 0;
public V getValue() { return value; }
public K getKey() { return key; }

Interactive Tools for This Topic

FAQ

What does Generic Class with Type Bounds print when run?
No setup needed: run the file and look for labeled lines like `42 > 10:`, `Pair:` in the output.