Java1.8什么情况下可以使用双冒号写法,代码列子
时间: 2023-12-03 07:42:48 浏览: 75
Java 1.8中双冒号写法也称为方法引用,主要用于简化Lambda表达式中的方法调用,其使用情况包括:
1. 用于引用静态方法
```
public class MethodReferenceExample {
public static void sayHello() {
System.out.println("Hello");
}
public static void main(String[] args) {
Runnable r = MethodReferenceExample::sayHello;
Thread t = new Thread(r);
t.start();
}
}
```
2. 用于引用实例方法
```
public class MethodReferenceExample {
public void sayHello() {
System.out.println("Hello");
}
public static void main(String[] args) {
MethodReferenceExample obj = new MethodReferenceExample();
Runnable r = obj::sayHello;
Thread t = new Thread(r);
t.start();
}
}
```
3. 用于引用构造方法
```
public class MethodReferenceExample {
private String message;
public MethodReferenceExample(String message) {
this.message = message;
}
public static void main(String[] args) {
Function<String, MethodReferenceExample> constructor = MethodReferenceExample::new;
MethodReferenceExample obj = constructor.apply("Hello");
System.out.println(obj.message);
}
}
```
阅读全文