gpt4 book ai didi

继承类或其子类的 Java 类

转载 作者:行者123 更新时间:2023-12-01 12:25:58 25 4
gpt4 key购买 nike

我有一个基地class A提供一些功能和子类 B extends AA 之上提供附加功能.

假设类(class)C , D ,和E延长A ,我将如何构造 C 的类, D ,和E延伸B相反(不创建基本上重复 CDE 的新类)?

类(class)C , D ,和E延伸A除了扩展 B 之外,仍然需要.

例如(随意改进):

A = Ball - provides basic things that are shared by all balls
B = Beach ball - provides some beach ball specific things
C has a method roll() that could allow A or B to roll
D has a method bounce() that could allow A or B to bounce
E has a method spin() that could allow A or B to spin

Any ball can have all, some, or none of the features C, D, and E

目标是能够创建 A 类型的对象或B包括 {C, D, E} 集合中的功能无需为所有可能的组合创建类

最佳答案

在java中,一个类只能扩展一个类。如果您想要扩展 B 而不是 A 的 C、D 和 E 的实现,则必须创建新类。

但是,行为可以通过类层次结构的其他方式进行控制。

一种选择是使用 delegation pattern ,与接口(interface)结合:

interface MyInterface {
public void someMethod();
}
class A implements MyInterface {
public void someMethod() {
// do something
}
}
class B extends A {
public void someMethod() {
// do something different
}
}

class C implements MyInterface {
private final MyIntegerface delegate;
public C(MyIntegerface delegate) {
this.delegate = delegate;
}
public void someMethod() {
delegate.someMethod();
}
}

构造 C 对象的客户端将客户端希望 C 使用的委托(delegate)传递给它:

C x = new C(new A());
C y = new C(new B());

类 C 只有一种定义,但它的行为方式有多种。

关于继承类或其子类的 Java 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26332999/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com