今天舍友面了一家公司,面完后他发了面经,有一个问题印象比较深,对话如下:
面试官:Java支持多继承吗?
舍友:准确来说不支持,但是接口与接口之间可以允许多继承。
面试官:那假如我一定要用类来实现多继承,可以吗?
。。。
不会,于是上网找了资料,然后记录下来
Java除了可以用接口(Interface)实现多继承之外,还可以用内部类(inner Class)来实现多继承。但是用内部类来实现多继承的话,网上有争议,认为这不是严格的多继承,因为一般来说继承往往可以伴随上转型,但是内部类不行。不过抛开这个争议,个人认为了解多一个知识点是可以的
代码如下:
定义两个父类:
Father类:
package yoe.multiExtends;
public class Father {
public void father_method(){
System.out.println("father method");
}
}
Mother类:
package yoe.multiExtends;
public class Mother {
public void mother_method(){
System.out.println("mother_method");
}
}
定义一个子类:
Son类:
package yoe.multiExtends;
public class Son {
//定义一个成员内部类,继承Father类,并重写父类方法
public class inner_father extends Father{
@Override
public void father_method(){
super.father_method();
}
}
//定义一个成员内部类,继承mother类,并重写父类方法
public class inner_mother extends Mother{
@Override
public void mother_method(){
super.mother_method();
}
}
public void invoke_father_method(){
new inner_father().father_method();
}
public void invoke_mother_method(){
new inner_mother().mother_method();
}
//调用方法
public static void main(String[] args) {
Son son = new Son();
son.invoke_father_method();
son.invoke_mother_method();
}
}
运行结果如下:
father method
mother_methodProcess finished with exit code 0