1 接口中的默认方法
Java 8
为关键字 default
增加新的用途,即为接口添加默认方法(又称守卫方法或虚拟扩展方法)。其主要功能:在不破坏已使用接口的代码的情形下,为接口增加新的方法(接口的实现类都可以使用)。
package com.hcong.interfaces;
/**
* @Classname InterfaceWithDefault
* @Date 2023/4/1 16:19
* @Created by HCong
*/
interface InterfaceWithDefault {
void f1();
void f2();
default void f() {
System.out.println("InterfaceWithDefault f()");
}
}
public class Implementation implements InterfaceWithDefault {
@Override
public void f1() {
System.out.println("Implementation f1()");
}
@Override
public void f2() {
System.out.println("Implementation f2()");
}
public static void main(String[] args) {
InterfaceWithDefault iwd = new Implementation();
iwd.f1();
iwd.f2();
iwd.f();
}
}
Implementation f1()
Implementation f2()
InterfaceWithDefault f()
2 接口中的静态方法
Java 8
还允许在接口中添加静态方法,其主要功能为:可将接口视作成工具类。
package com.hcong.utils;
/**
* @Classname Operations
* @Date 2023/4/1 17:15
* @Created by HCong
*/
public interface Operations {
void execute();
static void runOps(Operations... ops) {
for (Operations op : ops) {
op.execute();
}
}
static void show(String msg) {
System.out.println(msg);
}
}
package com.hcong.interfaces;
import com.hcong.utils.Operations;
/**
* @Classname Machine
* @Date 2023/4/1 17:16
* @Created by HCong
*/
class Bing implements Operations {
@Override
public void execute() {
Operations.show("Bing");
}
}
class Crack implements Operations {
@Override
public void execute() {
Operations.show("Crack");
}
}
class Twist implements Operations {
@Override
public void execute() {
Operations.show("Twist");
}
}
public class Machine {
public static void main(String[] args) {
Operations.runOps(new Bing(), new Crack(), new Twist());
}
}
Bing
Crack
Twist
上述接口 Operations
中的 runOps()
方法体现了 “模版方法” 设计模式。