0

我在一定程度上理解多重继承和接口。是否可以使用多重继承来实现我的要求?

我有分别实现接口 InterA、InterB、InterC、InterD 的 A、B、C、D 类。我想要一个类 ABCD,它应该具有 A、B、C、D 的所有方法。然后我想要在类 ABCD 中可用的 InterA、InterB、InterC、InterD 中声明的方法。

我已经在 A、B、C、D 类中定义了 InterA、InterB、InterC、InterD 中的方法实现,我不想在 ABCD 类中再次定义这些方法。我怎样才能在 Java 中做到这一点?

4

4 回答 4

2

接口的目的是确保实现该接口的类将实现该接口中声明的所有方法。

例如:

public interface Flyer {

    public void fly();
}

上面的接口保证了任何实现 Flyer 接口的 Java 类都会有 fly 方法的实现,而不管飞行是如何实现的。

例如:

public class Bird implements Flyer {

    public void fly() {
        System.out.println("Bird is flapping");
    }
}

另一个例如:

public class Eagle implements Flyer {

    public void fly() {
        System.out.println("Eagle is soaring");
    }
}

有了接口,我确信尽管实现不同,fly() 方法仍然存在。

因此,如果您想要一个具有 4 个不同接口行为的类 ABCD,如接口 A、B、C 和 D 中指定的,那么您可以实现:

public class ABCD implements A,B,C,D {

    // methods here
}

通常,我们使用接口来继承行为,使用父/子类来继承模型。

那么我们如何使用 Flyer 界面呢?

示例代码:

public class FlyerTest {

    public static void main (String [] args) {
        Flyer flyer = new Eagle();
        flyer.fly();    // Prints out "Eagle is soaring"

        flyer = new Bird();
        flyer.fly();    // Prints out "Bird is flapping"
    }

}

如您所见,只要我有一个 Flyer,我就确信“fly”方法会有一个实现。这让我无需怀疑该方法是否真的存在。

这就是我们使用接口来继承行为的原因。

希望您对多重继承有更好的理解。

为了回答您的核心问题,面向对象的编程通常有助于促进代码重用。

于 2012-06-06T07:23:58.437 回答
1

由于Java 中没有多重继承,因此您必须求助于聚合

class ABCD implements InterA, InterB, InterC, InterD
{
   A implA;
   B implB;
   C implC;
   D implD;

   ABCD(A pimplA, B pimplB, C pimplC, D pimplD)
   {
     implA = pimplA;
     implB = pimplB;
     implC = pimplC;
     implD = pimplD;
  }


  // @overidde methods from InterA as return implA ->method();
  // @overidde methods from InterB as return implB ->method();
  // @overidde methods from InterC as return implC ->method();
  // @overidde methods from InterD as return implD ->method();
}

这样你只需要创建一些 A、B、C 和 D 的实例,并在构建 ABCD 时传递它们。然后ABCD 只需要调用他们的方法

通过这样做,您将重用 A、B、C 和 D 的实现

于 2012-06-06T07:21:04.567 回答
0

java中没有“真正的”多重继承这样的东西。你不能做某事。你public class D extends C,B,A {} 所能做的就是实现多个接口,或者你可以让 B 扩展 A,C 扩展 B 和 D 扩展 C

于 2012-06-06T07:20:42.723 回答
0

java中没有多重继承。为什么不直接在 ABCD 中创建这些类的对象并使用它们来访问这些类的方法呢?

于 2012-06-06T07:26:10.560 回答