在接口中新增了default、static修饰,使用default修饰方法时可以使该方法在接口中有方法体,解决了当接口中新增方法,所有的实现类都要改变的问题。
default使用方法:
public interface TestDefaultMethod {
default void test(){
System.out.println("Hello !!!!");
}
}
实现类:
public class TestDefaultMethodImpl implements TestDefaultMethod {
public static void main(String[] args) {
TestDefaultMethod t = new TestDefaultMethodImpl();
//创建完对象后可以直接使用接口中的default方法,感觉和继承相似
t.test();
}
}
static使用方法:
public interface TestDefaultMethod {
default void test(){
System.out.println("Hello !!!!");
}
static void test2(){
System.out.println("Hello static!");
}
}
实现类:
public class TestDefaultMethodImpl implements TestDefaultMethod {
public static void main(String[] args) {
TestDefaultMethod t = new TestDefaultMethodImpl();
t.test();
//和普通类一样,可以直接点出静态方法
TestDefaultMethod.test2();
}
}
现在的接口与抽象类的区别:
1,接口中不能有main方法,抽象类中可以有main方法。
2、接口中的default和static修饰的方法还是使用的public修饰,而抽象类中可以使用protected,private,public来修饰。