您的位置:首页 > 编程语言 > Java开发

java - 实战 - 在接口中定义方法的实现

2017-05-01 13:11 671 查看
接口的一般用法:

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

接口中方法的具体实现

当某一类别的功能都需要有工具类别的功能时,可以在接口中定义和实现这些工具类别的功能。例如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();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: