Generic Methods

We can define generic method or parameterized type method in generic class or in normal class as well. We will see both example

  • Generic Method in Generic class
  • Generic Method in Normal class

Generic Method in Generic Class

Generic method can use generic class' type parameter. Let's take one example

Example :




 class demo<T>
{
// Method will take two arguments of type T
// Method check() return true if a and b both having same reference
boolean check(T a, T b)
{
if(a==b)
return true;
else
return false;
}
}


class use
{
public static void main(String arg[])
{
demo<Integer> ob=new demo();
// creating two Integer variable.
Integer a=new Integer(10);
Integer b=a;
System.out.println("Result is:"+ob.check(a,b));
}
}
/*Output:
Result is:true
*/

In above code we have declared a method with two arguments a and b. Both arguments are type of T. Type of these parameter has been taken from generic class' type parameter.


Generic Method in Nomal(non-generic) Class

Generic method can be defined in a non-generic class. In this case parameterized types is specified in method declaration.


Syntax :

<type-arg-list> return-type method-name(method-arg-list) 

Example :



 class demo
{
// Method will take two arguments of type T
// Method check() return true if a and b both having same reference
<T> boolean check(T a, T b)
{
if(a==b)
return true;
else
return false;
}
}


class use
{
public static void main(String arg[])
{
demo<Integer> ob=new demo();
// creating two Integer variable.
Integer a=new Integer(10);
Integer b=a;
System.out.println("Result is:"+ob.check(a,b));
}
}
/*Output:
Result is:true
*/

Let's see check() method closely.


<T> boolean check(T a,T b)
 

Parameterised type is specified before return-type of the method. This method is returning boolean data value. check() method has two argument of same type specified in parameter-arg-list.

Let's see how generic method is called. For calling generic method simply pass arguments.


 ob.check(a,b)
 

Generic method calling is similar to normal method call.