Rebel
Rebel

Reputation: 13

Java, stacking classes

What would be the best/most efficient way to make a class that would contain other classes and it self could be added to an Array?

Basicaly I want to have class that holds 'name', 'val1' and 'val2' So I guessed the best way would be simply:

public class SubClass {

private String name;
private double val1;
private double val2;

public SubClass(String name, double val1, double val2) {
    this.setName(name);
    this.setVal1(val1);
            this.setVal2(val2);
}

With all the 'set' and 'get' methods in it. So I can have it as Array SubClass[]. But I also want an 'UpperClass' that I could add multiple 'SubClass' to it with UpperClass.add(SubClass1); But I also want the UpperClass to have its own 'name' and hold it all as and Array UpperClass[] too. I want it as Array to sum separate columns, so I could display it as:

UpperClassName   25    56
Sub1             10    20
Sub2             15    36    

I guess I could create SubClass(String UpperClassName) and then use setVal in which I would add Val1 of all other SubClasses in this UpperClass and then just put it all as an Array, that sounds kinda messy.

And Finaly I want the same UpperClass to be added to SuperClass but only as the 1st row of UpperClass. But that I think would be just the UpperClass with some minor modifications? To get:

UpperClassName 25 56
UpperCLassName 30 87
UpperClassName 20 78

Is there any simple(clean) way to do this?

Upvotes: 0

Views: 58

Answers (1)

JB Nizet
JB Nizet

Reputation: 692231

OK, so you want to have Trains, containing Cars, containing Persons. And you want to be able to know how much money each person has, but also how much money each car and each train has.

So you need

public class Person {
    private double money;

    public double getMoney()
        return money;
    }
    ...
}

public class Car {
    private List<Person> persons;

    public double getMoney {
        double result = 0.0;
        for (Person person: persons) {
            result += person.getMoney();
        }
        return result;
    }
    ...
}

public class Train {
    private List<Car> cars;

    public double getMoney() {
        double result = 0.0;
        for (Car car : cars) {
            result += car.getMoney();
        }
        return result;
    }
    ...
}

As simple as that. Just like real objects, Java objects can contain other objects.

Upvotes: 3

Related Questions