Search code examples
javainheritancesubclasssuperclass

Subclass and Superclass methods


I'm creating a monopoly game with different types of squares. Square is the Superclass and PropertySquare is the Subclass.

I've created a loop that rolls the dice and moves the players to a different square. The squares are in an array list and I am able to call the superclass methods on them. However, even if the squares are set to more specific types (subclass of square), I cannot call the subclass methods on them.

This is how I have initialised the squares in a board class.

private static final ArrayList<Square> squares = new ArrayList<Square>(40);
squares.add(1, new PropertySquare("Old Kent Road", 1, 60, "Brown"));
board.getSquare(pos).getName());

getName is a method in the superclass square. However, even if the square is a property type, I cannot call the methods in the PropertySquare class such as getPrice();

How would I change this or be able to call the subclass methods?


Solution

  • I assume board.getSquare() returns a Square, and Square doesn't have any getPrice() method, so you can't call getPrice() over an object declared as Square, even if the instance is actually a PropertySquare (a.k.a. polymorphism). To do so, you have to first cast to the specific subclass. For example:

    final Square square = board.getSquare(pos);
    if (square instanceof PropertySquare) {
        ((PropertySquare)square).getPrice();
    }