Question

I am making a couple of simple classes to calculate a few things in a monopoly game.

My first class (BoardSquare) has methods to get and set the playerid squarename and the number of houses on the square while I have another method calculating the rent based on how many houses are on the square with an if-statement.

My second class (House) has a method that gets how much a new house costs for the property in another if statement and then has a set method to set the house price.

My goal is to use the House class inside of the boardsquare class. What I mean is that instead of having an instance variable

    int houses;

to hold the number of houses on a square I use a variable of type House. In other words, rather than having a number of houses on a square you have either 0 or 1 Houses.

I know what I want to do I just don't know how to do it.

So I have an instance variable House houses; and my getHouses method reads

    public House getHouses(this is where i had int h(from the constructor) but I dont know what to put here now)
    {
    Whatever I need to put here to access the class House
    }

Hopefully you can understand what I am trying to accomplish. I would be grateful for any tip you can provide.

Was it helpful?

Solution

You want a Collection<House>.

Do not use LinkedList<House> unless you need specific behavior of a linked list. This also goes for ArrayList. You may want either of these as an implementation, but use the most abstract collection you can.

  • List is the order of the houses is important
  • Set if you want to enforce only one instance of each type of house (may not apply)

So:

Collection<House> houses = new ArrayList<House>();

public Collection<House> getHouses() {
    return houses;
}

public void addHouse(House newHouse) {
    houses.add(newHouse);
}

I've chosen an ArrayList implementation because it is efficient to add new elements to the end of the list. This is also true of LinkedList, but LinkedList adds additional overhead that makes it efficient to insert entries into the List. See the documentation for more information.

OTHER TIPS

Add an instance variable within the BoardSquare class as follows:

LinkedList<House> houses;

If there can only be 0 or 1 houses you can have an instance variable of type House, and an instance variable of type boolean called hasHouses.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top