JDK8以上提高开发效率有哪些(其一——接口的默认方法和静态方法)

本文详细介绍了Java接口中的抽象方法、默认方法及静态方法的定义与使用。通过具体代码示例展示了如何实现接口,调用默认方法和静态方法,并解释了方法重写的规则。

接口的默认方法和静态方法

public interface MyDSService {
//抽象方法
String abstractMethod();
}

public class MyDSServiceImpl implements MyDSService {
public String abstractMethod() {
return "execute abstract method";
}
}
public interface MyDSService {
//抽象方法
String abstractMethod();
//默认方法
default String defaultMethod(){
return "execute default method";
}
//静态方法
static String staticMethod(){
return "execute static method";
}
}

方法调用:

public class DSDemo {
public static void main(String[] args) {
//接口实现类实例对象
MyDSServiceImpl myDSService = new MyDSServiceImpl();
//调用默认方法
String defaultMethodResult = myDSService.defaultMethod();
System.out.println(defaultMethodResult);
//调用静态方法
System.out.println(MyDSService.staticMethod());
}
}
//方法重写
MyDSService service = new MyDSService() {
@Override
public String commonMethod() {
return null;
}
@Override
public String defaultMethod() {
return null;
}
};

普通方法必须实现,默认方法可以选择性重写,静态方法无法重写。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值