Home >Java >javaTutorial >How to define generic methods in generic interface in Java?

How to define generic methods in generic interface in Java?

WBOY
WBOYOriginal
2024-05-01 19:09:01742browse

In Java, to define a generic method in a generic interface, you need to: define the generic interface and specify the type parameters. Define a generic method in the interface and specify the method return type and interface type parameters.

如何在 Java 中定义泛型接口中的泛型方法?

Define generic methods in generic interfaces in Java

A generic interface is an interface that contains generic Type type parameters. A generic method is a method defined in an interface that can also contain generic type parameters.

How to define generic methods in generic interfaces:

  1. First define a generic interface:
public interface MyGenericInterface<T> {
    // ...
}
  1. Define a generic method in the interface:
public interface MyGenericInterface<T> {
    // ...
    
    <R> R myGenericMethod(T t);
}

Where:

  • 0f1763a9dfcc95d54eac98034f0cdcdd is the type of the return type of the generic method parameter.
  • 8742468051c85b06f0a0af9e3e506b5c is the type parameter of the interface.

Practical case:

Suppose we have a MyService class, which implements the MyGenericInterface interface:

public class MyService implements MyGenericInterface<String> {
    @Override
    public String myGenericMethod(String s) {
        return s.toUpperCase();
    }
}

Now, we can use the MyService class to call the myGenericMethod method:

MyService service = new MyService();
String result = service.myGenericMethod("hello");
System.out.println(result); // 输出:HELLO

The above is the detailed content of How to define generic methods in generic interface in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn