如何从Java中继承多个基类? [英] How to inherit from multiple base classes in Java?
本文介绍了如何从Java中继承多个基类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道我们可以使用接口继承来自多个类但是是否也可以继承状态?
如何从2个类继承带有定义的方法并将它们放在Java的第三个类中?
I know that we can use interfaces to inherit from multiple classes but is it possible to inherit the state as well?
How can I inherit methods with definitions from 2 classes and have them in a third class in Java?
推荐答案
Java中不允许多重继承。请改为使用委托和接口
Multiple inheritance is not allowed in Java. Use delegates and interfaces instead
public interface AInterface {
public void a();
}
public interface BInterface {
public void b();
}
public class A implements AInterface {
public void a() {}
}
public class B implements BInterface {
public void b() {}
}
public class C implements AInterface, BInterface {
private A a;
private B b;
public void a() {
a.a();
}
public void b() {
b.b();
}
}
从Java 8开始,可以使用默认方法。
Since Java 8 it's possible to use Default Methods in Interfaces.
这篇关于如何从Java中继承多个基类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文