Inheritance and arrays

I had a question about how inheritance works. I’m wanting to make an array representing a 2d tile based map. Originally, I had this array simply hold char’s for each coordinate (its for a roguelike). However, I’m realizing it could be very beneficial to instead have each coordinate hold a reference to the object that is positioned there. That way, I could stuff like this
objectMap[12][32].getIsSolid()
to determine if a certain x/y coordinate can be moved to by the player.

But I’m not entirely sure how to do this. My idea was to make all the game objects (players, monsters, walls, etc) inherit a common GameObject type. If so, could I make the array of out GameObject’s and since monsters, players, and walls all inherit game object, set individual cells of the array to any type of game object?

Basically my question comes down to how inheritance works. Basically, can an array of GameObjects only be set to “pure” GameObjects, or can they also be set to any object that inherits GameObjects?

Any object with a class extending GameObject would be allowed in the array too.

CopyableCougar4

Awesome, thanks for the quick reply!

If you’re interested in a reason, it’s polymorphism. If you don’t know about polymorphism, here’s a quick explanation: https://www.youtube.com/watch?v=0xw06loTm1k

Okay, so I started implementing it, and I have a question.
So I gave the example of objectMap[12][32].getIsSolid()
Do I need to have the method in both the base GameObject and the extended object? As I understand it so far, I do. But that would mean that the base GameObject would need to have every method of every extended object. Although I suppose that makes sense, because there needs to a be a fallback in case the particular object that the method call is sent to does not have that method in its extended type, it can fall back and use the method in the base GameObject. Am I understanding that correctly?

You need that method in GameObject (unless you are using abstract classes) and any extending classes can override it.

CopyableCougar4

This is actually a common “challenge” when designing game objects using inheritance. It comes down to put the most common methods into the root [icode]GameObject[/icode] class and if you need more special ones you need to ask the object if it is of the desired type and then cast it accordingly:


GameObject current=objectMap[12][32]:
if( current instanceof Enemy ) ((Enemy)current).beNasty();

What comes handy is, that [icode]instanceof[/icode] is not only true when the object is exactly of the desired type, it is sufficient to be an inherited type or an implemented interface, too. So if you have a subclass of [icode]Enemy[/icode] like [icode]EnemyTower[/icode], it would also qualify as an [icode]Enemy[/icode] for the [icode]instanceof[/icode] test, and the above code would execute beNasty() on an [icode]EnemyTower[/icode] instance.