Generic Methods
Paul Ngugi
Posted on July 4, 2024
A generic type can be defined for a static method. You can define generic interfaces (e.g., the Comparable interface in Figure below (b)) and classes (e.g., the GenericStack class in here).
You can also use generic types to define generic methods. For example, the code below defines a generic method print (lines 13β17) to print an array of objects. Line 9 passes an array of integer objects to invoke the generic print method. Line 10 invokes print with an array of strings.
To declare a generic method, you place the generic type immediately after the keyword static in the method header. For example,
public static <E> void print(E[] list)
To invoke a generic method, prefix the method name with the actual type in angle brackets. For example,
GenericMethodDemo.<Integer>print(integers);
GenericMethodDemo.<String>print(strings);
or simply invoke it as follows:
print(integers);
print(strings);
In the latter case, the actual type is not explicitly specified. The compiler automatically discovers the actual type.
A generic type can be specified as a subtype of another type. Such a generic type is called bounded. For example, the code below revises the equalArea method in TestGeometricObject.java, to test whether two geometric objects have the same area. The bounded generic type (line 9) specifies that E is a generic subtype of GeometricObject. You must invoke equalArea by passing two instances of GeometricObject.
An unbounded generic type is the same as . To define a generic type for a class, place it after the class name, such as GenericStack. To define a generic type for a method, place the generic type before the method return type, such as void max(E o1, E o2).
Posted on July 4, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.