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] |
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());
}
}
Output2
Ram
Click the below link to download the code:
No comments:
Post a Comment