MCA
GENERICS // ENTERPRISE CODE // ABSTRACT FACTORY // GENERICS // ENTERPRISE CODE // ABSTRACT FACTORY //
BACK TO SYLLABUS
MEDIUM

GENERICS

Type parameters and generic programming

CONCEPTS

01Generic Classes
02Generic Methods
03Bounded Type Parameters (extends)
04Wildcards (?, ? extends, ? super)
05Type Erasure
06Creating generic data structures

SYNTAX_DEMO

Type-safe collections
class Box<T> {
    private T item;
    
    public void set(T item) { this.item = item; }
    public T get() { return this.item; }
}

public class Main {
    public static void main(String[] args) {
        Box<String> stringBox = new Box<>();
        stringBox.set("Hello Generics");
        System.out.println(stringBox.get());
        
        Box<Integer> intBox = new Box<>();
        intBox.set(123);
        System.out.println(intBox.get() * 2);
    }
}