默认方法在接口中如何实现?请用代码示例说明接口中默认方法的定义和使用方式。

// 1. 定义包含默认方法的接口
interface MyInterface {
    // 抽象方法
    void abstractMethod();

    // 默认方法
    default void defaultMethod() {
        System.out.println("这是接口中的默认方法实现。");
    }
}

// 2. 实现接口的类
class MyClass implements MyInterface {
    @Override
    public void abstractMethod() {
        System.out.println("这是抽象方法的实现。");
    }

    // 可以选择不重写默认方法
}

// 3. 测试类
public class Main {
    public static void main(String[] args) {
        MyClass myClass = new MyClass();
        myClass.abstractMethod(); // 调用抽象方法
        myClass.defaultMethod();  // 调用默认方法
    }
}

详细说明

  1. 接口中的默认方法定义:

    • 接口中可以通过 default 关键字定义默认方法。默认方法必须有一个实现体。
    • 默认方法的目的是在不破坏现有实现的情况下,为接口添加新功能。
  2. 默认方法的特点:

    • 默认方法可以被实现类直接调用,无需重写。
    • 如果实现类需要修改默认方法的行为,可以重写该方法。
    • 默认方法可以与其他方法(抽象方法、静态方法)共存于接口中。
  3. 示例解析:

    • 接口 MyInterface 定义了一个抽象方法 abstractMethod 和一个默认方法 defaultMethod。
    • 类 MyClass 实现了 MyInterface 接口,但只重写了抽象方法,没有重写默认方法。
    • 测试类 Main 创建了 MyClass 的对象,并调用其抽象方法和默认方法。
  4. 运行结果:

    这是抽象方法的实现。
    这是接口中的默认方法实现。
    
  5. 默认方法的实际应用场景:

    • 扩展接口功能:例如,List 接口在 Java 8 中新增了 sort 默认方法,所有实现类都可以直接使用该方法。
    • 解决多重继承问题:如果一个类实现了多个接口,而这些接口有相同的默认方法,可以通过重写该方法来解决冲突。
  6. 注意事项:

    • 默认方法可以调用接口中的其他方法。
    • 默认方法的访问修饰符是 public,不能是 private 或 protected。

进一步示例

interface InterfaceA {
    default void commonMethod() {
        System.out.println("InterfaceA 的默认方法");
    }
}

interface InterfaceB {
    default void commonMethod() {
        System.out.println("InterfaceB 的默认方法");
    }
}

class MyClass implements InterfaceA, InterfaceB {
    @Override
    public void commonMethod() {
        InterfaceA.super.commonMethod(); // 显式调用 InterfaceA 的默认方法
    }
}

public class Main {
    public static void main(String[] args) {
        MyClass myClass = new MyClass();
        myClass.commonMethod(); // 输出:InterfaceA 的默认方法
    }
}

在这个例子中,MyClass 实现了两个接口 InterfaceA 和 InterfaceB,它们都有一个名为 commonMethod 的默认方法。为了避免冲突,MyClass 必须重写 commonMethod,并通过 InterfaceA.super.commonMethod() 显式指定调用的方法。

总结来说,默认方法是 Java 8 引入的重要特性,它为接口提供了向后兼容的能力,同时解决了多重继承中的一些问题。通过合理使用默认方法,可以提高代码的灵活性和可维护性。