Java接口新特性

1、在接口中,可以直接添加静态方法。

该静态方法作为接口的类方法,可以直接使用。不需要依托某个实现类。

2、在接口中,可以直接添加非抽象的实例方法。

在实例方法的申明中,需要增加default关键字修饰,因此这种方法也称为默认方法。他是接口自带的方法。接口被实现后,实例可以直接使用这些默认方法,同时如果对默认方法需要重写时,可以直接重写即可。

这两点新特性相对于java8之前的版本来说,可以说有质的改变。

public interface SourceInterface 
 2 {
 3     int a = 5;
 4     int b = 10;
 5 
 6     public static int add() 
 7     {
 8         return a + b;
 9     }
10 
11     public static void reset() 
12     {
13         // do sth
14     }
15 
16     public default int f1()
17     {
18         return a;
19     }
20 
21     public default void f2()
22     {
23         // do sth
24     }
25 }
26 
27 class learnCode
28 {
29     public void userInterface()
30     {
31         int xx = SourceLearning.add();
32         SourceLearning.reset();
33         SourceLearning instance = new SourceLearning()
34         {
35             @Override
36             public void f2()
37             {
38                 // do sth 、
39             }
40         };
41         instance.f1();
42         instance.f2();
43         //int y=instance.add(); 注意这句会编译错误
44     }
45 }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值