為什么要單獨寫個java8新特性,一個原因是我目前所在的公司用的是jdk8,并且框架中用了大量的java8的新特性,如上篇文章寫到的stream方法進行過濾map集合。stream方法就是接口collection中的default方法。所以準備專門寫寫關于java8新特性的文章,雖然現在10已經發布了。但還是要認真的去了解下新版本的變化。
static方法
java8中為接口新增了一項功能:定義一個或者更多個靜態方法。用法和普通的static方法一樣。
代碼示例
1
2
3
4
5
6
7
8
|
public interface interfacea { /** * 靜態方法 */ static void showstatic() { system.out.println( "interfacea++showstatic" ); } } |
測試
1
2
3
4
5
|
public class test { public static void main(string[] args) { interfacea.show(); } } |
結果
interfacea++showstatic
注意,實現接口的類或者子接口不會繼承接口中的靜態方法
default方法
在接口中,增加default方法, 是為了既有的成千上萬的java類庫的類增加新的功能, 且不必對這些類重新進行設計。 比如, 只需在collection接口中
增加default stream stream(), 相應的set和list接口以及它們的子類都包含此的方法, 不必為每個子類都重新copy這個方法。
代碼示例
實現單一接口,僅實現接口
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
public interface interfacea { /** * 靜態方法 */ static void showstatic() { system.out.println( "interfacea++showstatic" ); } /** * 默認方法 */ default void showdefault() { system.out.println( "interfacea ++showdefault" ); } } /**先只實現這個接口 * @author: curry * @date: 2018/7/31 */ public class interfaceaimpl implements interfacea{ } |
測試
1
2
3
4
5
6
|
public class test { public static void main(string[] args) { interfacea.showstatic(); new interfaceaimpl().showdefault(); } } |
結果
interfacea++showstatic
interfacea ++showdefault
如果接口中的默認方法不能滿足某個實現類需要,那么實現類可以覆蓋默認方法。
實現單一接口,重寫接口中的default方法
1
2
3
4
5
6
7
8
9
|
public class interfaceaimpl implements interfacea{ /** * 跟接口default方法一致,但不能再加default修飾符 */ @override public void showdefault(){ system.out.println( "interfaceaimpl++ defaultshow" ); } } |
測試
1
2
3
4
5
6
|
public class test { public static void main(string[] args) { interfacea.showstatic(); new interfaceaimpl().showdefault(); } } |
結果
interfacea++showstatic
interfaceaimpl++ defaultshow
實現多個接口,且接口中擁有相同的default方法和static方法
新創建個接口interfaceb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
/** * @author: curry * @date: 2018/7/31 */ public interface interfaceb { /** * 靜態方法 */ static void showstatic() { system.out.println( "interfaceb++showstatic" ); } /** * 默認方法 */ default void showdefault() { system.out.println( "interfaceb ++showdefault" ); } } |
修改實現類
1
2
3
4
5
|
public class interfaceaimpl implements interfacea,interfaceb{ @override public void showdefault() { system.out.println( "interfaceaimpl ++ showdefault" ); } |
測試結果
interfacea++showstatic
interfaceaimpl ++ showdefault
總結
看了接口中新增的這個新特性,感覺還是不錯的,內容也比較簡單。需要注意一點就是如果實現多個接口時,每個接口都有相同的default方法需要重寫該方法。
以上所述是小編給大家介紹的java8新特性之interface中的static方法和default方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:http://www.cnblogs.com/zhenghengbin/p/9398682.html