userDSSR
userDSSR

Reputation: 657

Creating an Inheritance/Composition Structure in Java

I am looking for advise on approaches to the following situation. I think an inheritance structure will be helpful, to reduce the synchronization code. Any recommendation on the ideal way to create this model or point me to a similar example.

The model is shown below.

There are several GrandParents. A GrandParent can have several Parents and similarly a Parent can have several children. There seems to be two "inheritance" structure, one for Parent/Child and the other for "IncomeStatements".

The "grandIncomeStatement" and the "parentIncomeStatement" are a cumulative Income Statement of its Children as well its own IncomeStatement. They have to in synch whenever there are any changes to the "myIncomeStatement".

For now, I have created a "class IS(IncomeStatement)" which has common attributes without any inheritance and written code around changes - to the IncomeStatements at each level.

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

Upvotes: 0

Views: 71

Answers (1)

ajc
ajc

Reputation: 1735

A different approach would be to have Person and it having list of children.

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;
}

Edit: So you can probably have a recursive way to calculate the familyIncome (you'll obviously have a stricter access control, proper getters/setters)

Upvotes: 2

Related Questions