Building Generic Interfaces

by | Apr 11, 2021 | Java

Home » Java » Building Generic Interfaces

Building Generic Interfaces

The key idea behind generic programming is to code in such a manner that is valid for various types of elements. Rather than restricting the usage of the source code to a particular rubric, generic classes, interfaces, and methods generalize the execution. Like generic classes, generic interfaces can also be declared. Other than generalizing the interface, the basic functionality of this kind of interface is the same as a normal interface.

The following code is an interface of type Integer. This code will later be modified in the article to create a generic interface.

class MyClass implements MyInterface <Integer> {
public void myMethod (Integer i)
{
System.out.println (“Hello World” + i);
}
}

Generic Interfaces

Generic interfaces, like generic classes, can be declared in Java in the following way:

Sample Code

interface MyInterface <T>
{
//<T> refers to the fact that the interface does not adhere to only one particular datatype.
void myMethod (T t);
{
class MyClass implements MyInterface <Integer>
{
public void myMethod (Integer i)
{
System.out.println (“Hello World” + i);
}
}

In this code snippet given above, a generic interface is defined. This is followed by a class that implements the interface with the integer type. The type parameter of the generic interface is T. The class that implements a specific generic interface type need not be generic.

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author