接口的静态方法的定义和使用

1、从Java1.8开始,接口当中允许定义静态方法。

语法格式:

public static 返回值类型 方法名称(参数列表){
        方法体
}

接口的静态方法不能用 abstract 或 default 来修饰。

2、接口静态方法的使用:

注意事项:不能通过接口实现类的对象来调用接口当中的静态方法。

public class Program2{
    public static void main(String[] args) {
        ImplementationClass a = new ImplementationClass();
        a.kk();    // 报错
    }
}


class ImplementationClass implements InterfaceTest{
//    该接口无抽象类,不用实现
}

interface InterfaceTest{
    public static void kk(){

    }
}

正确用法:通过接口名称,直接调用其中的静态方法.

语法格式:

接口名称.静态方法名(参数);

接口中定义一个静态方法:

public class Program2{
    public static void main(String[] args) {
        InterfaceTest.kk();     // 编译通过
    }
}


class ImplementationClass implements InterfaceTest{
//    该接口无抽象类,不用实现
}

interface InterfaceTest{
    public static void kk(){

    }
}
经验分享 程序员 微信小程序 职场和发展