从java到你,所以问题可能是微不足道的。有两个类 -Something和SomethingGroup。受到以下事实的启发:在 android-framework 中,它ViewGroup继承自以及将混合和存储在一个列表中View的便利性,直接继承自:SomethingSomethingGroupSomethingGroupSomething
class Something {
private String name;
private int count;
public Something(String name, int count) {
this.name = name;
this.count = count;
}
public int getCount() {
return count;
}
}
class SomethingGroup extends Someting {
private String name;
ArrayList<Something> children;
SomethingGroup(String name, Something ... children) {
// super(и вот что ему сюда передать?)
this.name = name;
this.children = new ArrayList<>(Arrays.asList(children));
}
public int getCount() {
int count = 0;
for(Something s : children) {
count += s.getCount();
}
return count;
}
}
问题出在财产count上。在创建对象Something时,我们知道它的值,可以直接将其传递给构造函数,而在创建SomethingGroup这个值时,这个值是“间接”传递的,必须进行计算。在这种情况下如何行事?
解决了这样的问题:
想不出更好的了
如果您使用的是 Java 8,那么您可以更清楚地描述您的解决方案: