Java Program on Generic Classes
Free Java courses with 37 real-time projects - Learn Java
Program 1
package dataflair; import java.util.*; class MyClass<T> { T n; MyClass(T n) { this.n=n; } public String toString() { return (" "+n); } } public class TestMain { public static void main(String[] args) { // User Define Generic class MyClass<Integer>M1=new MyClass<Integer>(120); MyClass<String>M2=new MyClass<String>("Hello Data Flair"); MyClass<Double>M3=new MyClass<Double>(56.77); // MyClass<int>M4=new MyClass<int>(234); System.out.println(M1); System.out.println(M2); System.out.println(M3); // Inbuild Generic class // ArrayList<Integer> A=new ArrayList<Integer>(); // A.add(500); // A.add(200); // A.add(400); // A.add(500); // // ArrayList<String> B=new ArrayList<String>(); // B.add("First"); // B.add("Second"); // B.add("Third"); // // System.out.println(A); // // System.out.println(B); // A.add(100); // A.add("hello"); // A.add(45.66); // A.add(true); // System.out.println(A); } }
Program 2
package dataflair; class MyClass1<T,V> { T m; V n; MyClass1(T m,V n) { this.m=m; this.n=n; } public String toString() { return(" "+m+" "+n); } } public class TestMain1 { public static void main(String[] args) { MyClass1<Integer,String>M1; M1=new MyClass1<Integer,String>(101,"Vivek"); MyClass1<Double,Integer>M2; M2=new MyClass1<Double,Integer>(10.66,125); System.out.println(M1); System.out.println(M2); } }
Did we exceed your expectations?
If Yes, share your valuable feedback on Google