java接口定义的静态方法和默认如何在类实现的时候使用

在 JDK1.8,允许我们给接口添加两种非抽象的方法实现:

1、默认方法,添加 default 修饰即可;

2、静态方法,使用 static 修饰;示例如下:

这样可以实现接口的增强,那我们在类实现接口的时候如何用呢,我们举例来说明:

首先,我有一个Inteface的接口,如下:Inteface.java:

package Inteface;

public interface Inteface {
    default String get(String aa){
     System.out.print(aa);
     return "";
    }
    static void state(){
        System.out.print("state");
    };
}

  这里面我写了一个默认方法和静态方法,以实现接口的加强,那么,看一下我们的来实现接口是怎么写的吧:

IntefaceS.java:

package Inteface;

public class IntefaceS implements Inteface {
    public static void move() {
        System.out.print("hahah");
    }



    public static void main(String args[]) {
        IntefaceS inte = new IntefaceS();
        inte.get("123");
        Inteface.state();
    }
}

 由于在接口中使用了static关键字,所以这里再勒种使用的时候需要使用接口去掉方法,这里和类的继承非常相似了;

好吧,看结果 

原文地址:https://www.cnblogs.com/mmykdbc/p/8796325.html