Interface中的方法被default修饰

Interface中的方法被default修饰

在Java 8中,引入了default方法的概念,使得接口可以包含具体的方法实现。被default修饰的方法称为默认方法。这意味着接口不仅可以声明方法,还可以提供方法的默认实现。

默认方法的主要作用包括:

  1. 向后兼容:在不破坏现有实现的情况下,向接口添加新方法。例如,如果在一个已经广泛使用的接口中添加新方法,所有实现该接口的类都需要实现这个新方法。通过使用默认方法,可以为新方法提供一个默认实现,从而避免破坏现有代码。

  2. 代码复用:允许接口提供一些通用的功能实现,减少代码重复。

语法示例

public interface MyInterface {
    // 抽象方法
    void abstractMethod();

    // 默认方法
    default void defaultMethod() {
        System.out.println("This is a default method.");
    }
}

public class MyClass implements MyInterface {
    @Override
    public void abstractMethod() {
        System.out.println("This is an abstract method implementation.");
    }

    // 可以选择重写默认方法
    @Override
    public void defaultMethod() {
        System.out.println("This is an overridden default method.");
    }

    public static void main(String[] args) {
        MyClass myClass = new MyClass();
        myClass.abstractMethod(); // 输出: This is an abstract method implementation.
        myClass.defaultMethod();  // 输出: This is an overridden default method.
    }
}

在上述示例中,MyInterface接口包含一个抽象方法abstractMethod和一个默认方法defaultMethodMyClass实现了MyInterface,并且重写了默认方法defaultMethod

默认方法可以不被重写吗

默认方法可以不被重写。如果一个类实现了一个包含默认方法的接口,但没有重写该默认方法,那么该类将继承并使用接口中提供的默认实现。

示例

public interface MyInterface {
    // 抽象方法
    void abstractMethod();

    // 默认方法
    default void defaultMethod() {
        System.out.println("This is a default method.");
    }
}

public class MyClass implements MyInterface {
    @Override
    public void abstractMethod() {
        System.out.println("This is an abstract method implementation.");
    }

    // 没有重写 defaultMethod
    public static void main(String[] args) {
        MyClass myClass = new MyClass();
        myClass.abstractMethod(); // 输出: This is an abstract method implementation.
        myClass.defaultMethod();  // 输出: This is a default method.
    }
}

在这个示例中,MyClass实现了MyInterface,但没有重写默认方法defaultMethod。因此,当调用myClass.defaultMethod()时,将使用接口中提供的默认实现,输出 “This is a default method.”。

总结

  • 默认方法可以不被重写。如果不重写,类将使用接口中提供的默认实现。
  • 如果需要,可以选择重写默认方法以提供特定的实现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

你这个代码我看不懂

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值