Java8接口新特性

Java8新增了默认方法和静态方法;

对于已经发布的版本,不影响已有的实现情况下可以增加静态方法和默认方法
1)静态方法可以直接调用,不能被重写
2)默认方法需要通过实现类,重写后实例化后调用

/**
 * 接口可以有多个默认方法和静态方法
 */
public interface Java8Interface1 {
    //常量
    String constant = "java8";

    //抽象方法
    void doSomething();

    //默认方法
    default void defaultMethod1() {
        System.out.println("Java8Interface1's default method 1 is running...");
    }

    //默认方法可以有多个
    default void defaultMethod2() {
        System.out.println("Java8Interface1's default method 2 is running...");
    }

    //静态方法
    static void staticMethod1() {
        System.out.println("Java8Interface1's static method 1 is running...");
    }

    //静态方法也可以有多个
    static void staticMethod2() {
        System.out.println("Java8Interface1's static method 2 is running...");
    }

}
/**
 * 接口可以有多个默认方法和静态方法
 */
public interface Java8Interface2 {
    //常量
    String constant = "java8";

    //抽象方法
    void doSomething();

    //默认方法
    default void defaultMethod1() {
        System.out.println("Java8Interface2's default method 1 is running...");
    }

    //默认方法可以有多个
    default void defaultMethod2() {
        System.out.println("Java8Interface2's default method 2 is running...");
    }

    //静态方法
    static void staticMethod1() {
        System.out.println("Java8Interface2's static method 1 is running...");
    }

    //静态方法也可以有多个
    static void staticMethod2() {
        System.out.println("Java8Interface2's static method 2 is running...");
    }

}
//静态方法不能重写
public class Java8InterfaceImpl implements Java8Interface1,Java8Interface2{

    @Override
    public void doSomething() {

    }

    @Override
    public void defaultMethod1() {
        Java8Interface1.super.defaultMethod1();
        Java8Interface2.super.defaultMethod1();
    }

    @Override
    public void defaultMethod2() {
        Java8Interface1.super.defaultMethod2();
        Java8Interface2.super.defaultMethod2();
    }
}
public class Test{
    public static void main(String[] args) {
        //默认方法 和 抽象方法需实现类实例化后调用
        Java8Interface1 java8Interface = new Java8InterfaceImpl();
        //抽象方法重写后调用
        java8Interface.doSomething();
        //默认方法重写后调用
        java8Interface.defaultMethod1();
        java8Interface.defaultMethod2();
        //静态方法直接调用
        Java8Interface1.staticMethod1();
        Java8Interface2.staticMethod1();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值