java接口如何使用
接口的定义与语法
接口使用 interface 关键字定义,语法如下:

public interface InterfaceName {
// 常量(默认 public static final)
String CONSTANT = "value";
// 抽象方法(默认 public abstract)
void methodName();
// 默认方法(Java 8+)
default void defaultMethod() {
System.out.println("Default method");
}
// 静态方法(Java 8+)
static void staticMethod() {
System.out.println("Static method");
}
}
接口的实现
类通过 implements 关键字实现接口,必须重写所有抽象方法:

public class MyClass implements InterfaceName {
@Override
public void methodName() {
System.out.println("Implemented method");
}
}
多接口实现
一个类可实现多个接口,用逗号分隔:
public class MyClass implements Interface1, Interface2 {
// 重写所有接口的抽象方法
}
接口的继承
接口可通过 extends 继承其他接口,支持多继承:
public interface ChildInterface extends ParentInterface1, ParentInterface2 {
// 可扩展新方法或继承父接口方法
}
默认方法与静态方法
- 默认方法:提供默认实现,实现类可选择重写。
- 静态方法:直接通过接口名调用,例如
InterfaceName.staticMethod()。
接口的应用场景
- 定义规范:强制实现类遵循特定行为(如
Comparable接口)。 - 解耦设计:通过接口隔离实现与调用方(如
List接口与ArrayList实现)。 - 多态支持:通过接口引用指向不同实现类。
示例代码
interface Animal {
void eat();
}
class Dog implements Animal {
@Override
public void eat() {
System.out.println("Dog eats bones");
}
}
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog();
myDog.eat(); // 输出: Dog eats bones
}
}
通过接口可实现灵活的系统设计,尤其在需要多态或定义通用规范时。






