如何调用java接口
调用 Java 接口的基本方法
定义接口
接口通过 interface 关键字声明,包含抽象方法(默认 public abstract)和常量(默认 public static final)。
interface MyInterface {
void methodName();
int CONSTANT_VALUE = 10;
}
实现接口
类使用 implements 关键字实现接口,需重写所有抽象方法。
class MyClass implements MyInterface {
@Override
public void methodName() {
System.out.println("Method implementation");
}
}
通过对象调用
实例化实现类后,可直接调用接口方法。
MyInterface obj = new MyClass();
obj.methodName(); // 输出: Method implementation
多接口实现与继承
实现多个接口
一个类可同时实现多个接口,用逗号分隔。
interface InterfaceA { void methodA(); }
interface InterfaceB { void methodB(); }
class MultiImpl implements InterfaceA, InterfaceB {
@Override public void methodA() { /* 实现A */ }
@Override public void methodB() { /* 实现B */ }
}
接口继承
接口可通过 extends 继承其他接口,支持多重继承。
interface ParentInterface { void parentMethod(); }
interface ChildInterface extends ParentInterface {
void childMethod();
}
默认方法与静态方法
默认方法
Java 8 允许接口定义默认方法(default),实现类可直接使用或重写。
interface DefaultExample {
default void defaultMethod() {
System.out.println("Default implementation");
}
}
静态方法
接口中的静态方法(static)通过接口名直接调用。
interface StaticExample {
static void staticMethod() {
System.out.println("Static method");
}
}
// 调用方式
StaticExample.staticMethod();
函数式接口与 Lambda
函数式接口
仅含一个抽象方法的接口可使用 Lambda 表达式简化实现。
@FunctionalInterface
interface FunctionalExample {
void execute();
}
// Lambda 调用
FunctionalExample func = () -> System.out.println("Lambda");
func.execute();
常用函数式接口
Java 内置 java.util.function 包提供常用函数式接口,如 Predicate、Consumer 等。
Predicate<String> isEmpty = s -> s.isEmpty();
System.out.println(isEmpty.test("")); // 输出: true
实际应用示例
回调机制
通过接口实现回调模式,解耦调用逻辑。
interface Callback {
void onComplete(String result);
}
class Task {
void execute(Callback callback) {
callback.onComplete("Task done");
}
}
// 使用匿名类实现回调
new Task().execute(new Callback() {
@Override
public void onComplete(String result) {
System.out.println(result);
}
});
策略模式
利用接口灵活切换算法策略。

interface Strategy {
int compute(int a, int b);
}
class AddStrategy implements Strategy {
@Override public int compute(int a, int b) { return a + b; }
}
class Context {
private Strategy strategy;
void setStrategy(Strategy s) { this.strategy = s; }
int execute(int a, int b) { return strategy.compute(a, b); }
}
// 调用示例
Context ctx = new Context();
ctx.setStrategy(new AddStrategy());
ctx.execute(5, 3); // 输出: 8






