01 接口中的默认方法和静态方法

1 接口中的默认方法

Java 8 为关键字 default 增加新的用途,即为接口添加默认方法(又称守卫方法或虚拟扩展方法)。其主要功能:在不破坏已使用接口的代码的情形下,为接口增加新的方法(接口的实现类都可以使用)。

package com.hcong.interfaces;

/**
 * @Classname InterfaceWithDefault
 * @Date 2023/4/1 16:19
 * @Created by HCong
 */
interface InterfaceWithDefault {
    void f1();

    void f2();

    default void f() {
        System.out.println("InterfaceWithDefault f()");
    }
}

public class Implementation implements InterfaceWithDefault {
    @Override
    public void f1() {
        System.out.println("Implementation f1()");
    }

    @Override
    public void f2() {
        System.out.println("Implementation f2()");
    }

    public static void main(String[] args) {
        InterfaceWithDefault iwd = new Implementation();
        iwd.f1();
        iwd.f2();
        iwd.f();
    }
}

Implementation f1()
Implementation f2()
InterfaceWithDefault f()

2 接口中的静态方法

Java 8 还允许在接口中添加静态方法,其主要功能为:可将接口视作成工具类。

package com.hcong.utils;

/**
 * @Classname Operations
 * @Date 2023/4/1 17:15
 * @Created by HCong
 */
public interface Operations {
    void execute();

    static void runOps(Operations... ops) {
        for (Operations op : ops) {
            op.execute();
        }
    }

    static void show(String msg) {
        System.out.println(msg);
    }
}

package com.hcong.interfaces;

import com.hcong.utils.Operations;

/**
 * @Classname Machine
 * @Date 2023/4/1 17:16
 * @Created by HCong
 */

class Bing implements Operations {
    @Override
    public void execute() {
        Operations.show("Bing");
    }
}

class Crack implements Operations {
    @Override
    public void execute() {
        Operations.show("Crack");
    }
}

class Twist implements Operations {
    @Override
    public void execute() {
        Operations.show("Twist");
    }
}

public class Machine {
    public static void main(String[] args) {
        Operations.runOps(new Bing(), new Crack(), new Twist());
    }
}

Bing
Crack
Twist

上述接口 Operations 中的 runOps() 方法体现了 “模版方法” 设计模式。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

是聪聪黄吖

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

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

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

打赏作者

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

抵扣说明:

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

余额充值