Skip to content

Program 9 : Generics

Implement a generic class with multiple type parameters and create a simple example using generics to showcase their usage.

java
class GenericsDemo{
	static class TwoGen<T, V> {
	    T ob1;
	    V ob2;
		
	    TwoGen(T o1, V o2) {
	        ob1 = o1;
	        ob2 = o2;
	    }
		
	    void showTypes() {
	        System.out.println("Type of T is " 
		        + ob1.getClass().getName());
	        
	        System.out.println("Type of V is " 
		        + ob2.getClass().getName());
	    }
		
	    T getOb1() { return ob1; }
		
	    V getOb2() { return ob2; }
	}

	public static void main(String[] args){
		int num = 20;
		String str = "A Line to Print";
		
		TwoGen<Integer, String> demo = new TwoGen<>(num, str);
		
		demo.showTypes();
		
		System.out.println("The vales are " + demo.getOb1() 
			+ " and " + demo.getOb2());
	}
}
Type of T is java.lang.Integer
Type of V is java.lang.String
The vales are 20 and A Line to Print

Made with ❤️ for students, by a fellow learner.