java8的接口增加了default方法和static方法,访问权限为public。
接口的static方法和类的static方法区别,我们先来看一下类的static方法。
类的static方法、属性可以被继承不能被重写,只能被隐藏,举例如下
//父类 public class fatherclass{ static void print(){ System.out.println("father static"); } } //子类 public class childclass extends fatherclass { static void print(){ System.out.println("child static"); } } public static void main(String[] args) { fatherclass father=new childclass(); father.print(); }
此时输出结果为father static,说明子类并没有覆盖父类的static方法,此时根据声明类型来选择实际调用方法,而没有通过对象实际类型来选择。
接口的static方法不能被继承,无论是类还是子接口都不能继承父类的static方法,static属性可以被继承不能被重写。
接口的default方法可以被继承也可以被重写。若一个类实现的两个接口中有相同的default方法,此时发生冲突,两种解决方案。
方法一:指定重写具体接口的default方法。
方法二:直接重写冲突的default方法。本质相同。
//接口1 public interface testInterface1 { default void test(){ System.out.println("default Interface1"); } } //接口2 public interface testInterface2 { default void test(){ System.out.println("default Interface2"); } } public class childclass extends fatherclass implements testInterface,testInterface2 { //方法一 @Override public void test() { testInterface.super.test(); } //方法二 @Override public void test() { System.out.println("new default"); }
Java8新特性之接口的默认方法和静态方法
最新推荐文章于 2022-05-18 09:06:51 发布