jdk8 interface - default & static

1 篇文章 0 订阅

default & static 需要方法体

default

在接口中,增加default方法, 是为了既有的成千上万的Java类库的类增加新的功能, 且不必对这些类重新进行设计。

比如, 只需在接口中增加default void print(), 它们的实现类默认实现此方法, 不必为每个子类都重新实现这个方法。

public interface InterfaceA {
    
    default void print() {
        System.out.println("interface A - print()");
    };
}

public class InterfaceImpl implements InterfaceA {

}

public class Test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
       new InterfaceImpl().print();
    }   
}

也可以重写default方法,当实现多个接口,而其中含有相同的default方法名时,实现类需要重新default方法

static

与普通static方法一样

public interface InterfaceA {
    
    static void calculate() {
        System.out.println("interface A - calculate()");
    }
}

public class InterfaceImpl implements InterfaceA {

}

public class Test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        InterfaceA.calculate();       
    }   
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值