繁体   English   中英

如何同时访问不同类的两个方法?

[英]How to access both methods of different classes at the same time?

在一次采访中,有人问我以下问题。

假设有一个类使用drawShape()方法,另一个类B使用drawSquare()方法。

现在有一个第三类C扩展了A和B。

现在终于在我的课堂上,CI希望同时使用这两种方法。

如何同时获得这两种方法?

Now there is a third class C that extends both A and B

在Java中,您不能扩展到多个类。

如果您希望可以将B扩展到A,然后将C扩展到B,则您应该可以访问这两种方法

不要因为Java不支持扩展而扩展,而是可以使用interface:

interface IA{
   void drawshape();
}

inerface IB{
   void drawsquare();
}

class A implements IA{
    ...
}

class B implements IB{
    ...
}

class C implements IA,IB{
   private A a;
   private B b;

   void drawshape(){
     a.drawshape()
   } 

   void drawsquare(){
     b. drawsquare()
   }
}

Java不支持多个Class继承:一个Class只能扩展另一个Class。

相反,您可以使用Composition(在类中包含类)来实现要求的内容:

Class C {
    A a = new A();
    B b = new B();

    ...
}

现在, C可以通过执行a.drawShape()b.drawSquare()来访问任一方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM