Generics

The term generics means parameterized types. These types are important because they enable you to create classes, interfaces, and methods in which the type of data upon which they operate is specified as a parameter.

It is possible to create a single class by Using generics, for example, that automatically works with different types of data.

A class and interface, or method that operates on parameterized type is called generic, as in generic class or generic method.

Java always given the ability to create generalized classes, interfaces, and methods by operating through references of type Object.

Because Object is the super class of all other classes, an Object reference can refer to any type object.

Pre-generics code generics classes, interfaces, and methods used Object references to operate on various types of object. With generics, all casts are automatic and implicit.

Generics expand the ability to reuse code and let you do so safely and easily everything.

A Simple Generics Example with of a generic class. The following program defines two classes. The first is the generic class Gent, and the second is GentDemo, which uses Gent.


// A simple generic class.
// P is a type parameter that be replaced by real type
// when object of type Gent is created.
class Gent <T> {
	P obj; // declare an object of type P
	// Pass the constructor a reference to	
	// an object of type P. 
	Gent(P o) {
		obj = o;
	}
	// Return obj. 
	P getob() {
		return obj;
	}
	// Show type of P. 
	void showType() {
		System.out.println("Type of P is " + obj.getClass().getName());
	}
}


// Demonstrate the generic class. 

class GentDemo {
	public static void main(String args[]) {
		// Create a Gent reference for Integers. 
		Gent <Integer> iObj;
		// Create a Gent<Integer> object and assign its
		// reference to iObj.  Notice the use of autoboxing
		// to encapsulate value 88 within an Integer 
		object.iObj = new Gent <Integer> (88);
		// Show  type of data used by iObj.
		iObj.showType();
		// Get the value in iObj. Notice that
		// no cast is needed.
		int n = iObj.getob();
		System.out.println("value: " + n);
		System.out.println();
		// Create a Gent object for Strings. 
		Gent <String> strObj = new Gent <String> ("Generics Test");
		// Show  type of data used by strObj. 
		strObj.showType();
		// Get the value of strObj. Again, notice 
		// that no cast is needed. 
		String str = strObj.getob();
		System.out.println("value: " + str);
	}
}

The output produced by the program is :


Type of P is java.lang.Integer value: 88
Type of P is java.lang.String value: Generics Test

Generics Work Only with Objects

When we declaring an instance of a generic type then argument passed to the type parameter must be a class type. You can’t use a primitive type, like- int or char.

For example, with Gent, it is possible to pass any class type to P, but you cannot pass a primitive type to a type parameter. Therefore, the following declaration is illegal:


Gent<int> strObj = new Gent<int>(34); // Error that can't use primitive type

A Generic Class with Two Type Parameters

You can be declare more than one type parameter in a generic types. To specify two or more type parameters and simply use a comma-separated list.

For example, the following TwoGent class is a variation of the Gent class that has two types parameters:


// A simple generic class with two type
// parameters: P and N. 

class TwoGent <P,
N> {
	P obj1;
	N obj2;

	// Pass the constructor a reference to
	// an object of type P and an object of type N. 

	TwoGent(P o1, N o2) {
		obj1 = o1;
		obj2 = o2;
	}

	// Show types of P and N. 
	void showTypes() {
		System.out.println("Type of P : " + obj1.getClass().getName());
		System.out.println("Type of N : " + obj2.getClass().getName());
	}
	P getobj1() {
		return obj1;
	}
	V getobj2() {
		return obj2;
	}
}


// Demonstrate TwoGen. 

class SimpGent {
	public static void main(String args[]) {
		TwoGent <Integer, String> tgObj = new TwoGent <Integer, String> (88, "Generics");
		// Show the types. 
		tgObj.showTypes();
		// Obtain and show values.
		int N = tgObj.getob1();
		System.out.println("value: " + N);
		String str = tgObj.getobj2();
		System.out.println("value: " + str);
	}
}

The output from this program is shown here:


Type of P is java.lang.Integer 
Type of N is java.lang.String 
value: 88 
value: Generics

The General Form of a Generic Class

Generics syntax shown in the examples can be generalized, this is the syntax for declaring a generic class:


class class-name<type-param-list> { // ...
Here is the syntax for declaring a reference to a generic class:
class-name<type-arg-list> var-name = new class-name<type-arg-list>(cons-arg-list);

Creating a Generic Method

It is possible to declare a generic method that use one or more type parameters for self. it is possible to create a generic method that enclosed within a non-generic class.

Example:
This program declares a non-generic class called GMethDemo and a static generic method within that class called isnum(). The isnum() method determines if an object is a member of an array. It can used any type of object and array as long as the array contains objects that are compatible with the object being sought.


// Demonstrate a simple generic method :
class GMethDemo {
	// Determine if an object is in an array. 
	static <M, N extends M> boolean isnum(M x, N[] y) {
		for (int i = 0; i < y.length; i++)
		if (x.equals(y[i])) return true;
		return false;
	}
	public static void main(String args[]) {
		// Use isnum() on Integers. 
		Integer nums[] = {5, 6, 7, 8, 9};
		if (isIn(5, nums)) System.out.println("5 is in nums");
		if (!isIn(11, nums)) System.out.println("11 is not in nums");
		System.out.println();
		// Use isnum() on Strings. 
		String strs[] = {"seven", "two", "three", "four", "nine"};
		if (isnum("four", strs)) System.out.println("four is in strs");
		if (!isnum("seven", strs)) System.out.println("Six is not in strs");
		// Oops! Won't compile! Types must be compatibles.
		//    if(isnum("three", nums)) 
		//      System.out.println("three is in strs"); 
	}
}

The output from the program is shown here:


5 is in nums 11 is not in nums
three is in strs 
Six is not in strs

Generic Constructors

It is also possible that constructors to be generic, even if their class is not.

For example,


// Using a generic constructor. 
class GentCons {
	private double val; <T extends Number> GentCons(P arg) {
		val = arg.doubleValue();
	}
	void showval() {
		System.out.println("val: " + val);
	}
}

class GentConsDemo {
	public static void main(String args[]) {
		GenCons test = new GentCons(101);
		GenCons test2 = new GentCons(133.5 F);
		test.showval();
		test2.showval();
	}
}

The output is:


val: 101.0 
val: 133.5

Because the GentCons( ) specifies a parameter of a generic type, which must be subclass of Number, GentCons( ) can be called with any type of numeric type, including Integer, Float, or Double.

GentCons is not generic class, its constructor is generic.

Generic interfaces

Generic interfaces are just like as generic classes. Example- Let's create interface called MinMax interface that declares the methods min( ) and max( ), which expected to return the minimum and maximum value of some set of objects.


// A simple generic interface example.
// A min/max interface. 
interface MinMax <N extends Comparable <N>> {
	N min();
	N max();
}

// Now the implement MinMax 

class MyClass <N extends Comparable <N>> implements MinMax <N> {
	N[] vals;
	MyClass(N[] o) {
		vals = o;
	}
	// Return  minimum value in vals.
	public P min() {
		N vl = vals[0];
		for (int i = 1; i < vals.length; i++)
		if (vals[i].compareTo(vl) < 0) vl = vals[i];
		return vl;
	}
	// Return  maximum value in vals. 
	public N max() {
		N vl = vals[0];
		for (int i = 1; i < vals.length; i++)
		if (vals[i].compareTo(vl)> 0) vl = vals[i];
		return vl;
	}
}

class GenINDemo {
	public static void main(String args[]) {
		Integer inums[] = {5, 9, 12, 8, 6 };
		Character chs[] = {'b','a','p','w'};
		MyClass <Integer> iobj = new MyClass <Integer> (inums);
		MyClass <Character> cobj = new MyClass <Character> (chs);
		System.out.println("Max value in inums: " + iobj.max());
		System.out.println("Min value in inums: " + iobj.min());
		System.out.println("Max value in chs: " + cobj.max());
		System.out.println("Min value in chs: " + cobj.min());
	}
}


The output is shown here:
Max value in inums: 12 
Min value in inums: 5 
Max value in chs: w 
Min value in chs: a

About Author

Myself KarthiQ, I am the author of this blog, I know ways to write a good article but some how I donot have the skills to make it to reach people, would you like help me to reach more people By sharing this Article in the social media.

Share this Article Facebook