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()); } }Output
2
Ram
Click the below link to download the code:https://sites.google.com/site/ramj2eev1/home/javabasics/GenericsDemo_GenericClass_App.zip?attredirects=0&d=1
Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/GenericsDemo_GenericClass_App
Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/47d09ebb24294f7b507419345f38ec4cde27d544/BasicJava/GenericsDemo_GenericClass_App/?at=master
See also:
No comments:
Post a Comment