class A implements Interface
class B extends A implements Interface.
class C extends A
What's the differences between B and C?
1、为了让人阅读源码时知道子类实现了该核心接口。就像很多人都知道 ArrayList实现了List接口就够了,而不需要知道它继承AbstractList的相关细节。
2、在不使用接口代理的情况下毫无差别,使用接口代理没有显示的实现会报错。
反射时 getClass().getMethods()都能获取到接口中的方法,但是 getClass().getInterfaces();C就获取不到Interface.class。
例子如下:
package com.xcy.inherit.repeatedImplements;
public interface Viewable {
default void view(){
System.out.println("viewing interface Viewable");
};
}
package com.xcy.inherit.repeatedImplements;
public class BasePhoto implements Viewable {
// @Override
// public void view() {
// System.out.println("viewing base photo");
// }
}
package com.xcy.inherit.repeatedImplements;
public class LandscapePhoto extends BasePhoto implements Viewable {
// @Override
// public void view() {
// System.out.println("viewing landscape photo");
// }
}
package com.xcy.inherit.repeatedImplements;
public class Selfie extends BasePhoto {
// 可以直接覆盖父类实现的接口方法, 而不用再在class声明中再写implement Viewable了
// @Override
// public void view() {
// super.view();
// System.out.println("viewing my selfie");
// }
}
package com.xcy.inherit.repeatedImplements;
import java.lang.reflect.Method;
public class Main {
public static void main(String[] args) {
testImplementation();
testRelection();
}
public static void testImplementation(){
Viewable basePhoto = new BasePhoto();
Viewable selfie = new Selfie();
Viewable landscape = new LandscapePhoto();
basePhoto.view();
selfie.view();
landscape.view();
}
public static void testRelection(){
Viewable basePhoto = new BasePhoto();
Viewable selfie = new Selfie();
Viewable landscape = new LandscapePhoto();
System.out.println("basePhoto has Viewable interface: " + hasInterface(basePhoto));
System.out.println("selfie has Viewable interface: " + hasInterface(selfie));
System.out.println("landscape has Viewable interface: " + hasInterface(landscape));
// 输出
// basePhoto has Viewable interface: true
// selfie has Viewable interface: false
// landscape has Viewable interface: true
}
private static boolean hasInterface(Viewable viewable){
Method[] methods = viewable.getClass().getMethods();//都能获取到Viewable中view()方法
Class<?>[] interfaces = viewable.getClass().getInterfaces();
for(Class<?> c: interfaces)
if (c.equals(Viewable.class))
return true;
return false;
}
}