0

For starters, I have two classes that are relevant: Enemies.java and Sarz.java. Enemies extends Sarz.

public class Enemies extends Sarz {

It has an array with some enemy objects inside.

enemies[0] = new Enemies("Dragon", 100, 100, "Cave");
enemies[1] = new Enemies("Saturn Fly Trap", 10, 15, "Forest");

In Sarz, I make an array of type Sarz and in it I store some randomly generated enemies.

Enemies e = new Enemies();
e.generateEnemies();

Sarz[][] map = new Sarz[5][5];

while (count < 4){
  row = r.nextInt(5);
  column = r.nextInt(5);
  if (map[row][column] == null){
    map[row][column] = e.enemies[r.nextInt(8)];
    System.out.println(map[row][column].getName() + " at " + row + "," + column);
    count++;
  }
}

My problem is that when I use that println statement to test, they have been stored correctly in random spots, but I cannot seem to get anything to return the enemy name to me. I have tried using Arrays.toString() and the getters and setters of the Enemies class, but they will not work on the map array because it is of type Sarz. I would like to be able to use map[row][column].getEnemyName() or at least something to return a String instead of Enemies@14ae5a5 at 1,0.

2 Answers 2

2

Since Enemies extends Sarz, hence you can cast a Sarz to an object of Enemies (if it is a valid one.) So, you can do:

System.out.println(((Enemies)map[row][column]).getEnemyName() + " at " + row + "," + column);
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! Could you explain why this works? Trying to learn from my mistakes here...
It works because you cast a Sarz to an object of Enemies. So now, it can use methods of Enemies.
0

Instead of casting the superclass to the subclass, if you need to call method getEnemyName() from the Sarz object, you should rethink your objects design to declare the method in the Sarz superclass and let the subclasses like Enemy inherit it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.