Friday, 9 June 2017

Java Tutorial: Generics in java | Java Generics [How to define a Generics class] ~ foundjava


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

Click the below Image to Enlarge
Java Tutorial: Generics in java | Java Generics [How to define a Generics class] 
MyGeneric.java
class MyGeneric<T>
{
    T obj;

    void add(T obj)
    {
        this.obj = obj;
    }

    T get()
    {
        return obj;
    }
}
GenericDemo.java
/*
 * Code to use the generic class.
 */
public class GenericDemo
{
    public static void main(String[] args)
    {
        useInteger();  
        useString();
    }

    private static void useInteger()
    {
        MyGeneric<Integer> myGeneric=new MyGeneric<Integer>();  
        myGeneric.add(2);  
        //myGeneric.add("peter");//Compile time error  
        System.out.println(myGeneric.get());
    }
    
    private static void useString()
    {
        MyGeneric<String> myGeneric=new MyGeneric<String>();  
        myGeneric.add("Ram");  
        System.out.println(myGeneric.get());
    }
}
Output
2
Ram
Click the below link to download the code:

CLICK HERE

No comments:

Post a Comment