Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Java – Generic Method

Similar to generic classes, we can create generic methods.

Java allows creating a generic method in a non-generic class.

Example

 class OOPs 
 {
     String name;
	
     OOPs(String name)
     {
         this.name = name;	
     }
	
     public void displayName() 
     {
         System.out.println(name);	
     }
 }

 class ProcedureOriented 
 {
     String name;
	
     ProcedureOriented(String name)
     {
         this.name = name;	
     }
	
     public void displayName() 
     {
         System.out.println(name);	
     }
 }

 class GenericMethodTest 
 {
     public <T extends OOPs> void callMethod(T t)
     {
         t.displayName();
     }
	
     public static void main(String args[])
     {
         OOPs n1 = new OOPs("Java");
         OOPs n2 = new OOPs("c#");
         ProcedureOriented p = new ProcedureOriented("C");
		
         GenericMethodTest t1 = new GenericMethodTest();
         GenericMethodTest t2 = new GenericMethodTest();
         GenericMethodTest t3 = new GenericMethodTest();
		
         t1.callMethod(n1);
         t1.callMethod(n2);
      // t1.callMethod(p);
     }
 }

Output

Java
c#

If we removed comments at line,

t1.callMethod(p);

We will get compile time error because the argument p is not of OOP’s type or its child class.

 

Leave a reply