今天看HashMap源码时发现一种奇怪的接口实现方法。有趣,所以记录一哈
在这里就不贴源码了,
以下是我自己写的一个例子来说明这种情况
1,接口
public interface Root {
void next();
}
2,父类
public class Parent {
public void next() {
System.out.println("next next next");
}
}
3,子类
public class Child extends Parent implements Root{
}
4,测试类
public static void main(String args[]){
Child second=new Child();
Root root= (Root) second;
root.next();
}
输出
next next next
从这里看,子类Child虽然实现了Root接口,但没有具体的实现方法,父类Parent虽然没有直接实现Root接口,但有和接口内相同的方法,
通过测试,在这种姿势的写法,最终执行到了Parent的next方法。说明这种情况下也可以实现接口
这应该和java的单继承有关吧,个人猜测,编译器在编译的时候,会现在子类找接口的实现方法,找不到的情况递归到父类去找,
所以只要保证子类或父类有接口的所有方法的实现即可