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.
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:
public interface MyGenericInterface<T> { // ... }
public interface MyGenericInterface<T> { // ... <R> R myGenericMethod(T t); }
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(); } }
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!