多重继承的实现
利用接口
此时实现接口,多半仅是在实现抽象方法。但如果我想使用多个类中的一些具体实现呢?
利用内部类
class Father {
public int strong(){
return 9;
}
}
class Mother {
public int kind(){
return 8;
}
}
class Son {
/**
* 内部类继承Father类
*/
class Father_1 extends Father{
public int strong(){
return super.strong() + 1;
}
}
class Mother_1 extends Mother{
public int kind(){
return super.kind() - 2;
}
}
public int getStrong(){
return new Father_1().strong();
}
public int getKind(){
return new Mother_1().kind();
}
}
public class K {
public static void main(String[] args) {
Son son = new Son();
System.out.println("Son 的Strong:" + son.getStrong());
System.out.println("Son 的kind:" + son.getKind());
}
}
这里定义了两个内部类,他们分别继承父亲Father类、母亲Mother类,且都可以非常自然地获取各自父类的行为,这是内部类一个重要的特性:内部类可以继承一个与外部类无关的类,保证了内部类的独立性,正是基于这一点,多重继承才会成为可能。
参考链接
- https://www.cnblogs.com/chenssy/p/3389027.html
还没有评论,来说两句吧...