Home > Java > javaTutorial > body text

How to define generic methods in generic interface in Java?

WBOY
Release: 2024-05-01 19:09:01
Original
736 people have browsed it

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> {
    // ...
}
Copy after login
  1. Define a generic method in the interface:
public interface MyGenericInterface<T> {
    // ...
    
    <R> R myGenericMethod(T t);
}
Copy after login

Where:

  • <R> is the type of the return type of the generic method parameter.
  • <T> 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();
    }
}
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template