Java接口的三种实现方式

一.使用关键字implements实现接口

//格式
public class 类名 implements 接口名{

}

//示例
public class test{
    public static void main(String[] args){
        A a=new A();
        a.eat();
    }
}

//定义接口
interface Inter{
    void eat();
}

//定义实现接口类
class A implements Inter{
    public void eat(){
        System.out.println("吃饭");
    }
}

二.匿名内部类实现接口

//格式
new 接口名(){
    public 返回值类型 重写的方法名(){
        
        }
};

//示例
public class Test1 {
    public static void main(String[] args) {
        //使用匿名内部类实现接口
        Inter inter=new Inter() {
            public void eat() {
                System.out.println("吃饭");
            }
        };
        inter.eat();
    }
}

interface Inter{
    void eat();
}

三.Lambda表达式实现接口

public class Test1 {
    public static void main(String[] args) {
        go(new Inter() {
            public void eat() {
                System.out.println("去吃饭");
            }
        });
        go(() -> System.out.println("去吃饭"));
    }

    public static void go(Inter inter){
        inter.eat();
    }
}

interface Inter{
    void eat();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值