Generics (Cont.)


Generic Functions
We can also write generic functions that can be called with different types of arguments based on the type of arguments passed to generic method. The compiler handles each method.

GenericMethod.java (generic methods)
// To show the working of user-defined generic functions 
class GenericMethod {
  public static void main( String[ ] args ) { 
    // Calling generic method with Integer argument 
    genericDisplay( Integer.parseInt( args[0] ) ); 
    // Calling generic method with String argument 
    genericDisplay( args[1] ); 
    // Calling generic method with double argument 
    genericDisplay( Double.parseDouble( args[2] ) ); 
  } 
  // A generic method example
  static<T> void genericDisplay( T element ) {
    System.out.println( element.getClass( ).getName( ) + " = " + element );
  }
}
shell> java GenericMethod   (integer)   (string)   (double)

      Output:

Advantages of Generics
Programs that uses generics have many benefits over non-generic code:


      When we were kids, we used to be afraid of the dark.    
      But when we grew up, the electricity bill made us afraid of the light!