Java8新特性——接口静态方法

概述

从Java8开始接口发生两个大的改变,一个是引入了default关键字,另个一个就是允许静态方法的存在。

default关键字在《Java8新特性default关键字,引出Java多继承问题》一文中详细描述过了。现在我们就挖掘一下接口静态方法与传统类的静态方法有什么区别。

接口中的静态方法

public interface Hello {
    static void sayHello(){
        System.out.println("Hello World!");
    }
 
    static void main(String[] args) {
        Hello.sayHello();
    }
}
interface TestInterface1 {
    static void sayHello(){
        System.out.println("TestInterface1 Hello");
    }
}
interface TestInterface2 extends TestInterface1 {
    
}
public class Test implements TestInterface1,TestInterface2{
    public static void main(String[] args) {
        TestInterface2.sayHello();//编译报错
    }
}

这段代码在JDK8的环境下是能够编译通过并运行的。但是在接口中的静态方法有什么不同呢?

接口中的静态方法不能继承

interface TestInterface1 {
    static void sayHello(){
        System.out.println("TestInterface1 Hello");
    }
}
public class Test implements TestInterface1{
    public static void main(String[] args) {
        TestInterface1.sayHello();
        Test.sayHello();//编译报错
    }
}

原因:

因为一个类是可以实现多个接口的,如果接口中的静态方法的方法前面相同,就会发生继承冲突。所以索性就从继承这个层面阻断冲突的发生。反过来看由于接口中的字段是可以被继承的,所以实际上接口中的字段是存在继承冲突的。

interface TestInterface1 {
    String hello="TestInterface1";
    
}
interface TestInterface1 {
    String hello="TestInterface2";
}
public class Test implements TestInterface1,TestInterface2{
    public static void main(String[] args) {
        System.out.println(Test.hello);//这里会报错
    }
}

总结

Java8中接口中静态字段可以被继承(默认用public static final修饰),静态方法不会继承,只能通过接口名调用。

posted @ 2019-04-26 18:12  听到微笑  阅读(1)  评论(0编辑  收藏  举报  来源