java 中使用 interface 关键字定义接口,并在类中通过 implements 关键字实现该接口。接口可以包含抽象方法、默认方法和静态方法,类实现接口时必须提供所有非默认方法的实现。这种机制支持多态和代码解耦。

如何定义一个包含抽象方法的接口
定义一个接口时,使用 interface 关键字后跟接口名称,内部声明抽象方法。例如,定义一个名为 Animal 的接口,其中包含一个抽象方法 speak()。任何实现该接口的类都必须重写 speak() 方法。

public interface Animal {
void speak();
}
public class Dog implements Animal {
@Override
public void speak() {
System.out.println("Woof!");
}
}
public class Main {
public static void main(String[] args) {
Animal dog = new Dog();
dog.speak(); // 输出: Woof!
}
}
上述代码定义了 Animal 接口和 Dog 类。运行 Main 类会调用 Dog 的 speak() 方法并输出 "Woof!"。
立即学习“Java免费学习笔记(深入)”;
如何在接口中添加默认方法
从 Java 8 开始,接口可以包含默认方法,使用 default 关键字修饰。默认方法提供了默认实现,实现类可以选择覆盖它。例如,在 Animal 接口中添加一个默认方法 move()。

public interface Animal {
void speak();
default void move() {
System.out.println("Moving...");
}
}
public class Dog implements Animal {
@Override
public void speak() {
System.out.println("Woof!");
}
}
public class Main {
public static void main(String[] args) {
Animal dog = new Dog();
dog.speak(); // 输出: Woof!
dog.move(); // 输出: Moving...
}
}
上述代码在 Animal 接口中添加了默认方法 move()。Dog 类不需要实现 move(),可以直接调用。运行 Main 类会输出 "Woof!" 和 "Moving..."。
接口中的静态方法如何使用
接口还可以包含静态方法,使用 static 关键字修饰。静态方法属于接口本身,而不是实现类。例如,在 Animal 接口中添加一个静态方法 create()。
public interface Animal {
void speak();
default void move() {
System.out.println("Moving...");
}
static Animal create(String type) {
if ("dog".equals(type)) {
return new Dog();
} else {
throw new IllegalArgumentException("Unknown animal type");
}
}
}
public class Dog implements Animal {
@Override
public void speak() {
System.out.println("Woof!");
}
}
public class Main {
public static void main(String[] args) {
Animal dog = Animal.create("dog");
dog.speak(); // 输出: Woof!
}
}
上述代码在 Animal 接口中添加了静态方法 create(),用于根据类型创建动物实例。运行 Main 类会创建 Dog 实例并调用其 speak() 方法,输出 "Woof!"。


















