java

来源:互联网 发布:淘宝鹰眼 编辑:程序博客网 时间:2024/04/30 02:45
  1. 接口的一般用法:

    接口常用于功能的解耦,接口通过interface定义。在Interface中定义方法,但是不需要实现方法。接口的作用是规范接口实现具备的功能,似于是类的模板。例如Map接口,规范了所有Map实现都需具备的功:size(),isEmpty()等方法。

  2. 接口中方法的具体实现

    当某一类别的功能都需要有工具类别的功能时,可以在接口中定义和实现这些工具类别的功能。例如Map.Entry接口的定义的工具类别的功能,如下:

public static <K extends Comparable<? super K>, V> Comparator<Map.Entry<K,V>> comparingByKey() {            return (Comparator<Map.Entry<K, V>> & Serializable)                (c1, c2) -> c1.getKey().compareTo(c2.getKey());        }

在接口中定义的方法只能是static或者default修饰的方法。据不同的修饰名,而调用方法的方式不同。

//接口public interface Interface01<K,V> {    K getKey();    V getValue();    V setValue(V value);    // default修饰,表示对象级的方法;static修饰,表示类级的方法;    public default void say(){        System.out.println("interface method..");    }}//实现类,不需要实现say方法;public class Extends01<K,V>     implements Interface01<K, V>{    private final K key;    private V value;    public Extends01(K key,V value){        this.key = key;        this.value = value;    }    @Override    public K getKey() {        return key;    }    @Override    public V getValue() {        return value;    }    @Override    public V setValue(V value) {        V oldValue = this.value;        this.value = value;        return oldValue;    }}//测试public class InterfaceTest {    public static void main(String[] args) {        Interface01<Integer, String> s             =new Extends01<Integer, String>(1,"sky");        System.out.println(s.getValue());        System.out.println(s.getKey());        System.out.println(s.setValue("yun"));        System.out.println(s.getValue());        // default修饰,通过实现类对象进行调用;        s.say();        // static修改,通过接口名进行调用。        //Interface01.say();    }}
0 0