为什么 Java 8 在接口中引入了默认方法?
java 8object oriented programmingprogramming更新于 2025/9/19 16:44:17
Java 中的接口类似于类,但它只包含 final 和 static 的抽象方法和字段。
它是方法原型的规范。每当您需要指导程序员或制定约定来指定类型的方法和字段应该如何定义时,都可以定义接口。
示例
interface MyInterface{
public void display();
public void setName(String name);
public void setAge(int age);
}
如果您需要您的类遵循某个规范,您需要实现所需的接口并为该接口中的所有抽象方法提供方法体。
例如,如果您想创建一个线程,一种方法是实现 Runnable 接口并为抽象方法 Run() 提供方法体。
示例
public class RunnableDemo implements Runnable {
private Thread t;
private String threadName;
RunnableDemo(String name) {
threadName = name;
}
public void run() {
System.out.println("implementation of the runnable method");
}
public void start () {
t = new Thread (this, threadName);
t.start ();
}
public static void main(String args[]) {
RunnableDemo r = new RunnableDemo("Thread_1");
r.start();
}
}
输出
Creating Thread_1 implementation of the runnable method
如果您没有提供接口的所有抽象方法的实现(您,实现),则会生成编译时错误。
示例
public class RunnableDemo implements Runnable {
private Thread t;
private String threadName;
RunnableDemo( String name) {
threadName = name;
System.out.println("Creating " + threadName );
}
/*public void run() {
System.out.println("implementation of the runnable method");
}*/
public static void main(String args[]) {
RunnableDemo r = new RunnableDemo( "Thread-1");
}
}
编译时错误
RunnableDemo.java:1: error: RunnableDemo is not abstract and does not override abstract method run() in Runnable
public class RunnableDemo implements Runnable {
^
1 error
如果接口中添加了新方法会怎样?
假设我们正在使用某个接口,并实现了该接口中的所有抽象方法,之后又添加了新的方法。
那么,除非在每个类中实现新添加的方法,否则所有使用此接口的类都将无法工作。
为了解决这个问题,Java8 引入了默认方法。
默认方法
默认方法也称为防御方法或虚拟扩展方法。您可以使用 default 关键字将默认方法定义为 −
default void display() {
System.out.println("This is a default method");
}
曾经在接口中为特定方法编写过默认实现。无需在已经使用(实现)此接口的类中实现它。
示例
以下 Java 示例演示了 Java 中默认方法的用法。
interface sampleInterface{
public void demo();
default void display() {
System.out.println("This is a default method");
}
}
public class DefaultMethodExample implements sampleInterface{
public void demo() {
System.out.println("This is the implementation of the demo method");
}
public static void main(String args[]) {
DefaultMethodExample obj = new DefaultMethodExample();
obj.demo();
obj.display();
}
}
输出
This is the implementation of the demo method This is a default method
注意 − 接口的所有方法都是公共的,因此不需要在它前面明确使用 public。

