gpt4 book ai didi

java - 在 Java 中创建继承/组合结构

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

我正在寻求有关解决以下情况的建议。我认为继承结构将有助于减少同步代码。关于创建此模型的理想方法的任何建议或向我指出类似的示例。

模型如下图所示。

有几个祖 parent 。祖 parent 可以有多个 parent ,同样 parent 可以有多个 child 。似乎有两种“继承”结构,一种用于父/子,另一种用于“损益表”。

“grandIncomeStatement”和“parentIncomeStatement”是其子项的累积损益表以及其自己的损益表。每当“myIncomeStatement”发生任何更改时,它们都必须保持同步。

现在,我创建了一个“类 IS(IncomeStatement)”,它具有公共(public)属性,没有任何继承,并围绕每个级别的 IncomeStatements 的更改编写了代码。

class GrandParent {
ObjectIS myIncomeStatement;
ObjectIS grandIncomeStatement;
}
class Parent {
ObjectIS myIncomeStatement;
ObjectIS parentIncomeStatement;
}
class Child {
ObjectIS myIncomeStatement;
}

最佳答案

另一种方法是拥有 Person 并拥有子列表。

public class Person {
List<Person> children;
ObjectIS myIncomeStatement;
ObjectIS familyIncomeStatement;

public ObjectIS getFamilyIncomeStatement() {
ObjectIS is = new ObjectIS();
for(Person p: children) {
is.income += p.familyIncomeStatement.income;
}
is.income += this.myIncomeStatement.income;
return is;
}
}

// sample objectIS class
public class ObjectIS {
private int income;
}

编辑:因此您可能可以采用递归方式来计算家庭收入(显然您将拥有更严格的访问控制,适当的 getter/setter)

关于java - 在 Java 中创建继承/组合结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47757034/

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