在一次采访中,我被问到以下问题。
假设有一个类 A 有一个方法drawShape()
,另一个类 B 有一个方法drawSquare()
。
现在有第三个类 C 扩展了 A 和 B。
现在终于在我的课堂上 CI 想要这两种方法。
如何同时获得这两种方法?
不要因为 Java 不支持而扩展,而是可以使用接口:
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 不支持多类继承:一个类只能扩展另一个类。
相反,您可以使用 Composition(在您的类中包含类)来实现所要求的内容:
Class C {
A a = new A();
B b = new B();
...
}
现在C
可以通过a.drawShape()
或访问任一方法b.drawSquare()
。
Now there is a third class C that extends both A and B
在 Java 中,您不能扩展到多个类。
如果您愿意,您可以将 B 扩展到 A,然后将 C 扩展到 B,这样您应该能够访问这两种方法