Java 子类实现父类已经实现的接口
2017-11-05 本文已影响0人
xiaofudeng
结论
假设有
class A implements Interface
class B extends A
-
class C extends A implements Interface
.
那么:
- B和C都可以向上转型为
Interface
- B和C在不覆盖接口定义的方法时都会用父类的实现
- 在反射方法
getInterfaces()
中, A和C类都会有Interface
, 但是B不会有Interface
验证
Viewable接口:
package interfaces;
/**
* Created by xiaofu on 17-11-5.
*/
public interface Viewable {
void view();
}
BasePhoto类:
package interfaces;
/**
* Created by xiaofu on 17-11-5.
*/
public class BasePhoto implements Viewable {
@Override
public void view() {
System.out.println("viewing base photo");
}
}
Selfie类:
package interfaces;
/**
* Created by xiaofu on 17-11-5.
*/
public class Selfie extends BasePhoto {
// 可以直接覆盖父类实现的接口方法, 而不用再在class声明中再写implement Viewable了
@Override
public void view() {
// super.view();
System.out.println("viewing my selfie");
}
}
Landscape类:
package interfaces;
/**
* Created by xiaofu on 17-11-5.
* 父类已经实现了Viewable接口
*/
public class LandscapePhoto extends BasePhoto implements Viewable {
@Override
public void view() {
System.out.println("viewing landscape photo");
}
}
Main类:
package interfaces;
/**
* Created by xiaofu on 17-11-5.
*/
public class Main {
public static void testImplementation(){
Viewable basePhoto = new BasePhoto();
Viewable selfie = new Selfie();
Viewable landscape = new LandscapePhoto();
basePhoto.view();
selfie.view();
landscape.view();
// 输出
// viewing base photo
// viewing my selfie
// viewing landscape photo
}
public static void testRelection(){
BasePhoto basePhoto = new BasePhoto();
BasePhoto selfie = new Selfie();
BasePhoto 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(BasePhoto photo){
Class<?>[] interfaces = photo.getClass().getInterfaces();
for(Class<?> c: interfaces)
if (c.equals(Viewable.class))
return true;
return false;
}
public static void main(String[] args) {
testImplementation();
testRelection();
}
}
如果实现的接口有类型参数
该类情况, 子类要么不声明implements直接Override父类中该接口的方法, 要么声明的时候只能用和父类一样的类型参数.
原因如下(原链接):
A class may not at the same time be a subtype of two interface types which are different parameterizations of the same generic interface (§9.1.2), or a subtype of a parameterization of a generic interface and a raw type naming that same generic interface, or a compile-time error occurs.
This requirement was introduced in order to support translation by type erasure (§4.6).