Generic Methods

A generic method defines its own formal type parameters. You can define a generic method in a generic or a nongeneric class.

package com.gs.corejava.collections;

public class Generic3 {

	static <T> void genericDisplay(T arg) {
		System.out.println(arg);
	}

	public static void main(String[] args) {
		genericDisplay(12);
		genericDisplay(13.4);
		genericDisplay("mohit");
	}
}
12
13.4
mohit

GENERIC METHODS DEFINED IN A NONGENERIC CLASS OR INTERFACE:

A nongeneric class doesn’t define type parameters. To define a generic method in a nongeneric class or interface, you must define the type parameters with the method, in its type parameter section. A method’s type parameter list is placed just after its access and nonaccess modifiers and before its return type. Because a type parameter could be used to define the return type, it should be known before the return type is used. An example

For a generic method (defined in a nongeneric class or inter-face), its type parameter list is placed just after the access and nonaccess modifiers and before its return type.

GENERIC METHODS DEFINED IN A GENERIC CLASS OR INTERFACE:

The following example defines a generic interface, and a generic method that defines its own type parameter.

Problem :

1)

2) What will be the output ?

3) What will be the output ?

Ans:

1)

Last updated

Was this helpful?