如何从Java中的多个基类继承?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2031759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to inherit from multiple base classes in Java?
提问by Anonymous
Possible Duplicates:
Cheat single inheritance in Java !!
Why is Multiple Inheritance not allowed in Java or C#?
Multiple Inheritance in 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?
我知道我们可以使用接口从多个类继承,但是否也可以继承状态?
如何从 2 个类中继承具有定义的方法并将它们放在 Java 中的第三个类中?
回答by Laurence Gonsalves
Short answer: You can't. Java only has multiple inheritance of interfaces.
简短的回答:你不能。Java只有接口的多重继承。
Slightly longer answer: If you make sure the methods you care about are in interfaces, then you can have a class that implements the interfaces, and then delegates to instances of the "super classes":
稍微长一点的答案:如果您确保您关心的方法在接口中,那么您可以拥有一个实现接口的类,然后委托给“超类”的实例:
interface Noisy {
void makeNoise();
}
interface Vehicle {
void go(int distance);
}
class Truck implements Vehicle {
...
}
class Siren implements Noisy {
...
}
class Ambulance extends Truck implements Noisy {
private Siren siren = new Siren();
public makeNoise() {
siren.makeNoise();
}
...
}
回答by Rob Oxspring
Java explicitly disallows multiple inheritance of implementation. You're left with using interfaces and composition to achieve similar results.
Java 明确禁止实现的多重继承。您只能使用接口和组合来实现类似的结果。
回答by albertein
You can not, Java doesn't support multiple inheritance. What you could do is composition.
你不能,Java 不支持多重继承。你可以做的是组合。
回答by Fabiano
Multiple inheritance is not allowed in Java. Use delegates and interfaces instead
Java 中不允许多重继承。改用委托和接口
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();
}
}
Since Java 8 it's possible to use Default Methodsin Interfaces.
从 Java 8 开始,可以在接口中使用默认方法。