利用内部类实现多继承
如何利用内部类实现多重继承,请看下面实例:儿子是如何利用多重继承来继承父亲和母亲的优良基因。
首先是父亲 Father 和母亲 Mother:
public class Father {
public int strong(){
return 9;
}
}
public class Mother {
public int kind(){
return 8;
}
}
重头戏在这里,儿子类 Son:
public 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 Test1 {
public static void main(String[] args) {
Son son = new Son();
System.out.println("Son 的Strong:" + son.getStrong());
System.out.println("Son 的kind:" + son.getKind());
}
}
----------------------------------------
Output:
Son 的Strong:10
Son 的kind:6
儿子继承了父亲,变得比父亲更加强壮,同时也继承了母亲,只不过温柔指数下降了。这里定义了两个内部类,他们分别继承父亲 Father 类、母亲类Mother类,且都可以非常自然地获取各自父类的行为,这是内部类一个重要的特性:内部类可以继承一个与外部类无关的类,保证了内部类的独立性,正是基于这一点,多重继承才会成为可能。