Thursday, 8 June 2017

Java Tutorial: Generics in java | Java Generics [Generic types] ~ foundjava


Click here to watch in Youtube :
https://www.youtube.com/watch?v=x5UTvcx9lvg&list=UUhwKlOVR041tngjerWxVccw

Click the below Image to Enlarge
Java Tutorial: Generics in java | Java Generics [Generic types] 

Java Tutorial: Generics in java | Java Generics [Generic types] 
Java Tutorial: Generics in java | Java Generics [Generic types] 
Java Tutorial: Generics in java | Java Generics [Generic types] 
Box.java
/**
 * Generic version of the Box class.
 * 
 * @param <T>
 *            the type of the value being boxed
 */
public class Box<T>
{
    // T stands for "Type"
    private T t;

    public void set(T t)
    {
        this.t = t;
    }

    public T get()
    {
        return t;
    }
}
GenericDemo.java
public class GenericDemo
{

    public static void main(String[] args)
    {
        Box<Integer> integerBox = new Box<Integer>();
        integerBox.set(new Integer(100));
        //integerBox.set("Ram"); //Compile time error
        Integer integerValue = integerBox.get();
        System.out.println("integerValue = "+integerValue);

        Box<String> stringBox = new Box<String>();
        stringBox.set("Peter");
        String strValue = stringBox.get();
        System.out.println("strValue = "+strValue);
        
    }

}
Output
integerValue = 100
strValue = Peter

Click the below link to download the code:

CLICK HERE

No comments:

Post a Comment