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.
Code
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
SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.URL Safety CheckerEvaluate a URL against common phishing red flags such as plain HTTP, embedded credentials, IP hosts, Punycode, and risky top-level domains.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.