Java 接口如何模拟多重继承?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3556652/
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 do Java Interfaces simulate multiple inheritance?
提问by Hymannad
I am reading "The Java Tutorial" (for the 2nd time). I just got through the section on Interfaces (again), but still do not understand how Java Interfaces simulate multiple inheritance. Is there a clearer explanation than what is in the book?
我正在阅读“Java 教程”(第二次)。我刚刚(再次)浏览了接口部分,但仍然不明白 Java 接口如何模拟多重继承。有没有比书上更清楚的解释?
采纳答案by Peter Tillemans
Suppose you have 2 kinds of things in your domain : Trucks and Kitchens
假设您的域中有两种东西:卡车和厨房
Trucks have a driveTo() method and Kitchens a cook() method.
卡车有一个 driveTo() 方法,而厨房有一个 Cook() 方法。
Now suppose Pauli decides to sell pizzas from the back of a delivery truck. He wants a thing where he can driveTo() and cook() with.
现在假设泡利决定从一辆送货卡车的后面卖比萨饼。他想要一个他可以用 driveTo() 和 cook() 的东西。
In C++ he would use multiple inheritance to do this.
在 C++ 中,他会使用多重继承来做到这一点。
In Java that was considered to be too dangerous so you can inherit from a main class, but you can "inherit" behaviors from interfaces, which are for all intents and purposes abstract classes with no fields or method implementations.
在 Java 中,这被认为太危险,因此您可以从主类继承,但您可以从接口“继承”行为,这些行为出于所有意图和目的都是没有字段或方法实现的抽象类。
So in Java we tend to implement multiple inheritance using delegations :
所以在 Java 中,我们倾向于使用委托来实现多重继承:
Pauli subclasses a truck and adds a kitchen to the truck in a member variable called kitchen. He implements the Kitchen interface by calling kitchen.cook().
Pauli 将卡车子类化,并在名为 kitchen 的成员变量中向卡车添加厨房。他通过调用 kitchen.cook() 来实现 Kitchen 接口。
class PizzaTruck extends Truck implements Kitchen {
Kitchen kitchen;
public void cook(Food foodItem) {
kitchen.cook(foodItem);
}
}
He is a happy man because he can now do things like ;
他是一个快乐的人,因为他现在可以做这样的事情;
pizzaTruck.driveTo(beach);
pizzaTruck.cook(pizzaWithExtraAnchovies);
Ok, this silly story was to make the point that it is no simulation of multiple inheritance, it is real multiple inheritance with the proviso that you can only inherit the contract, only inherit from empty abstract base classes which are called interfaces.
好吧,这个愚蠢的故事是要说明它不是模拟多重继承,它是真正的多重继承,条件是您只能继承契约,只能从称为接口的空抽象基类继承。
(update: with the coming of default methods interfacesnow can also provide some behavior to be inherited)
(更新:随着默认方法接口的出现,现在也可以提供一些可以被继承的行为)
回答by Mark Peters
It's pretty simple. You can implement more than one interface in a type. So for example, you could have an implementation of List
that is also an instance of Deque
(and Java does...LinkedList
).
这很简单。您可以在一种类型中实现多个接口。因此,例如,您可以有一个实现,List
它也是Deque
(Java 确实... LinkedList
)的一个实例。
You just can't inherit implementationsfrom multiple parents (i.e. extend multiple classes). Declarations(method signatures) are no problem.
您不能从多个父级继承实现(即扩展多个类)。 声明(方法签名)没有问题。
回答by Colin Hebert
It's not a simulation of multiple inheritance. In java you can't inherit from two classes, but if you implements two interfaces "it seems like you inherited from two different classes" because you can use your class as any of your two intefaces.
这不是多重继承的模拟。在 Java 中,您不能从两个类继承,但是如果您实现了两个接口,“似乎您是从两个不同的类继承的”,因为您可以将您的类用作两个接口中的任何一个。
For example
例如
interface MyFirstInteface{
void method1();
}
interface MySecondInteface{
void method2();
}
class MyClass implements MyFirstInteface, MySecondInteface{
public void method1(){
//Method 1
}
public void method2(){
//Method 2
}
public static void main(String... args){
MyFirstInterface mfi = new MyClass();
MySecondInterface msi = new MyClass();
}
}
This will work and you can use mfi and msi, it seems like a multi inheritance, but it's not because you don't inherit anything, you just rewrite public methods provided by the interfaces.
这会起作用,你可以使用mfi和msi,它看起来像一个多继承,但这不是因为你没有继承任何东西,你只是重写了接口提供的公共方法。
回答by Thomas Owens
I don't think they do.
我不认为他们这样做。
Inheritance is specifically an implementation-oriented relationship between implementations. Interfaces do not provide any implementation information at all, but instead define a type. To have inheritance, you need to specifically inherit some behaviors or attributes from a parent class.
继承具体是实现之间的面向实现的关系。接口根本不提供任何实现信息,而是定义一个类型。要进行继承,您需要专门从父类继承一些行为或属性。
I believe there is a question here somewhere specifically about the role of interfaces and multiple inheritance, but I can't find it now...
我相信这里有一个关于接口和多重继承的作用的问题,但我现在找不到了......
回答by Benjamin Wootton
It's not fair to say that interfaces 'simulate' multiple inheritance.
说接口“模拟”多重继承是不公平的。
Sure, your type can implement multiple interfaces and act as many different types polymorphically. However, you obviously won't inherit behaviour or implementations under this arrangement.
当然,您的类型可以实现多个接口并以多态方式充当许多不同的类型。但是,在这种安排下,您显然不会继承行为或实现。
Generally look at composition where you think you may need multiple inheritance.
通常查看您认为可能需要多重继承的组合。
OR A potential solution to achieving something multiple inheritance like is the Mixin interface - http://csis.pace.edu/~bergin/patterns/multipleinheritance.html. Use with care!
或实现多重继承的潜在解决方案是 Mixin 接口 - http://csis.pace.edu/~bergin/patterns/multipleinheritance.html。小心使用!
回答by david99world
given the two interfaces below...
鉴于下面的两个接口......
interface I1 {
abstract void test(int i);
}
interface I2 {
abstract void test(String s);
}
We can implement both of these using the code below...
我们可以使用下面的代码实现这两个......
public class MultInterfaces implements I1, I2 {
public void test(int i) {
System.out.println("In MultInterfaces.I1.test");
}
public void test(String s) {
System.out.println("In MultInterfaces.I2.test");
}
public static void main(String[] a) {
MultInterfaces t = new MultInterfaces();
t.test(42);
t.test("Hello");
}
}
We CANNOT extend two objects, but we can implement two interfaces.
我们不能扩展两个对象,但我们可以实现两个接口。
回答by Justin Niessner
There's really no simulation of multiple inheritance in Java.
在 Java 中确实没有模拟多重继承。
People will sometimes say that you can simulate multiple inheritance using Interfaces because you can implement more than one interface per class, and then use composition (rather than inheritance) in your class to achieve the behaviors of the multiple classes that you were trying to inherit from to begin with.
人们有时会说,您可以使用接口模拟多重继承,因为您可以为每个类实现多个接口,然后在您的类中使用组合(而不是继承)来实现您试图继承的多个类的行为开始。
回答by Michael Borgwardt
You're probably confused because you view multiple inheritance locally, in terms of one class inheriting implementation details from multiple parents. This is not possible in Java (and often leads to abuse in languages where it's possible).
您可能会感到困惑,因为您在本地查看多重继承,就一个类从多个父级继承实现细节而言。这在 Java 中是不可能的(并且在可能的情况下经常导致语言滥用)。
Interfaces allow multiple inheritance of types, e.g. a class Waterfowl extends Bird implements Swimmer
can be used by other classes as if it were a Bird
andas if it were a Swimmer
. This is the the deeper meaning of multiple inheritance: allowing one object to act like it belongs to several unrelated different classes at once.
接口允许类型的多重继承,例如 aclass Waterfowl extends Bird implements Swimmer
可以被其他类使用,就好像它是 a 一样Bird
,就好像它是 a 一样Swimmer
。这就是多重继承的深层含义:允许一个对象表现得好像它同时属于几个不相关的不同类。
回答by duffymo
You need to be precise:
你需要准确:
Java allows multiple inheritance of interface, but only single inheritance of implementation.
Java 允许接口的多重继承,但只允许实现的单一继承。
You do multiple inheritance of interface in Java like this:
您可以像这样在 Java 中对接口进行多重继承:
public interface Foo
{
String getX();
}
public interface Bar
{
String getY();
}
public class MultipleInterfaces implements Foo, Bar
{
private Foo foo;
private Bar bar;
public MultipleInterfaces(Foo foo, Bar bar)
{
this.foo = foo;
this.bar = bar;
}
public String getX() { return this.foo.getX(); }
public String getY() { return this.bar.getY(); }
}
回答by Benjamin Wootton
If it makes sense in your object model, you can of course inherit from one class and implement 1 or more interfaces as well.
如果它在您的对象模型中有意义,您当然可以从一个类继承并实现 1 个或多个接口。