在Java中,接口函数通常指的是接口中定义的抽象方法,这些方法在接口中声明为`public abstract`,并且没有方法体。接口函数可以通过Lambda表达式或方法引用来实现。下面是一些基本概念和示例:
函数式接口
函数式接口是只有一个抽象方法的接口,Java 8引入了`@FunctionalInterface`注解来标记函数式接口,确保接口中只有一个抽象方法。
示例
```java
@FunctionalInterface
public interface MyFunction {
int apply(int x);
}
// 使用函数式接口MyFunction
MyFunction myFunction = (x) -> x * x;
int result = myFunction.apply(5); // result 为25
接口函数的书写
接口函数的书写遵循以下格式:
```java
public interface InterfaceName {
// 抽象方法声明
returnType methodName(parameterList);
}
示例
```java
public interface MyInterface {
String getString();
}
// 实现接口
public class MyClass implements MyInterface {
@Override
public String getString() {
return "Hello, World!";
}
}
使用Lambda表达式实现接口函数
接口函数可以通过Lambda表达式来简洁地实现,例如:
```java
MyInterface myInterface = () -> "Hello, World!";
System.out.println(myInterface.getString());
使用方法引用来实现接口函数
方法引用是另一种实现接口函数的方式,它允许使用现有的方法来满足接口的要求:
```java
public class MyClass {
public String getString() {
return "Hello, World!";
}
}
MyInterface myInterface = new MyClass()::getString;
System.out.println(myInterface.getString());
常用函数式接口
Java 8引入了几个常用的函数式接口,如`Supplier`, `Consumer`, `Function`, `Predicate`等,它们分别用于不同的场景:
`Supplier
`:无参的,返回类型为`T`的对象。 `Consumer
`:有参的,无返回值,参数类型为`T`。 `Function
`:有参有返回值,参数类型为`T`,返回类型为`R`。 `Predicate
`:有参,返回`boolean`类型值。 示例
```java
// Supplier
Supplier
stringSupplier = () -> "Hello, World!"; System.out.println(stringSupplier.get());
// Consumer
Consumer
stringConsumer = s -> System.out.println(s); stringConsumer.accept("Hello, World!");
// Function
Function
stringToInteger = Integer::parseInt; System.out.println(stringToInteger.apply("1234"));
// Predicate
Predicate
isGreaterThanTen = n -> n > 10; System.out.println(isGreaterThanTen.test(20)); // true
以上是Java中接口函数的基本写法和使用示例。