介绍
目的:充分理解到继承和实现的概念。
继承:Java中,一个类继承只能继承一个类。
实现:Java中,一个类可以实现多个接口。
实践
interface Intera{
}
class Bimpl implements Intera{
}
class CExtend extends Bimpl{
}
public class ShowInterfaces {
/*
* 很多Java程序员把继承和实现概念混淆!
* 比如:我现在的CExtend对象能否通过反射获取到它所实现的接口??
*/
public static void main(String[] args) {
Intera a=new CExtend();
Class clazz=a.getClass();
Class []superInterfacesClass=clazz.getInterfaces();
for(Class i:superInterfacesClass){
System.out.println(i.getName());
}
System.out.println("###################分割线#####################");
Intera b=new Bimpl();
clazz=b.getClass();
superInterfacesClass=clazz.getInterfaces();
for(Class i:superInterfacesClass){
System.out.println(i.getName());
}
}
}
猜猜最后输出什么??
输出结果:
###################分割线#####################
bacejava.Intera
为什么呢??CExtend这个类明明实现了Intera这个接口,却获取不到接口??
嗯,对!其实实现这个接口的并不是CExtend这个类,而是它的父类Bimpl这个类实现了Intera接口。而Intera和CExtend并没有一点关系。
你说没关系??那为什么能够这样写??
Intera a=new CExtend();
其实啊!它中间过程有这样的步骤:
Intera a=(Intera)((Bimpl)new CExtend());
CExtend类是Bimpl的子类,所以CExtend对象可以强制转化为Bimpl对象类型。最终CExtend对象转换为Intera这个对象类型。
嗯,没错,就是这样!!!
希望各位读者以后注意!!!