Generics Concept

PHOTO EMBED

Wed May 29 2024 17:02:43 GMT+0000 (Coordinated Universal Time)

Saved by @exam123

public class Container<T> {
    private T obj;

    public Container(T obj) {
        this.obj = obj;
    }

    public T getObj() {
        return this.obj;
    }

    public void showType() {
        System.out.println("Type is: " + obj.getClass().getName());
    }

    public static void main(String[] args) {
        // Container for a String
        Container<String> c1 = new Container<>("Generics");
        String s = c1.getObj();
        System.out.println("String is: " + s);
        c1.showType();

        // Container for an Integer
        Container<Integer> c2 = new Container<>(123);
        int i = c2.getObj();
        System.out.println("Integer is: " + i);
        c2.showType();
    }
}
content_copyCOPY