In this video we are going to learn generic concept in java. what is generic and how it is important for code.

 

Crash Courses Playlist : https://www.youtube.com/playlist?list=PL0zysOflRCenCfUTpsGw9crgOih-VbNoT Generic in one video | Java Generic Full concept in 23 min in Hindi

 

 

Exmaple.java

import java.util.*;

public class Demo {

    public static void main(String[] args) {

        List<Integer> list = new ArrayList<>();
        // list.add("LCWD");
        list.add(123);

        List anotherList = new ArrayList();
        anotherList.add("LCWD");
        anotherList.add(12);
        anotherList.add(12.12);

        System.out.println(list);
        System.out.println(anotherList);

    }
}

 

Box.java

public class Box<T> {

    // Object class is top most parent class of all java classes

    T container;

    public Box(T container) {
        this.container = container;
    }

    public void performSomeTask() {
        if (container instanceof String) {
            System.out.println("length of " + container + " is " + (((String) this.container).length()));
        } else if (container instanceof Integer) {
            System.out.println("This is integer value " + container);
        }
    }

    public Object getValue() {
        return this.container;
    }
}

 

Example.java

import javax.swing.SpinnerDateModel;

public class Example {
    public static void main(String[] args) {

        Box<String> box = new Box<>("Wow this is amazing");
        System.out.println(box.getValue());
        System.out.println(box.container.getClass().getName());

        Box<Integer> box1 = new Box<>(121);
        System.out.println(box1.getValue());
        System.out.println(box1.container.getClass().getName());

        box.container = "subscribe to youtube channel";
        box1.container = 1452;
        Box<Boolean> box2 = new Box<>(true);
        System.out.println(box2.getValue());
        box.performSomeTask();
        box1.performSomeTask();

    }
}