Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use objects of different classes in one array?(Java)

a friend of mine came up with an idea for a racing game, and i'm trying to create that in java. now, i have made 3 classes for cars, 1 for player cars, 1 for computer(ai)cars and a main one that holds some variables like location (x,y on the screen) and name to name a few. the first 2 inherit from the last one. i hoped this would allow me to create one array with both the players and the computer players in it. this however doesnt work, and now my question:

is there any way it is possible to have an array with different kinds of objects in them, and if this is possible, how can i do it or are there any tutorials on it?

i have looked at interfaces, but i dont think that would do the trick, but please correct me if im wrong.

this was the idea that i had:

MainCar[] carsArray = new MainCar[totalPlayers];
for(int i = 0; i < totalHumanPlayers; i++)
{
  carsArray[i] = new PlayerCar();
}
for(int i = 0; i < totalComputerPlayers; i++)
{
  carsArray[i] = new ComputerCar();
}

the idea with it is that i can loop through all the players(human and computer) to draw them at their locations and to decide whos turn it is next turn

many thanks, and please forgive my english, i don't know if it's correct or not, not my first language :)

like image 536
javaNoobsForever Avatar asked Apr 21 '26 15:04

javaNoobsForever


1 Answers

Ok, with the second loop you are overwriting the values previously set, because you start at the same offset i=0.

I'd suggest something like:

for(int i = totalHumanPlayers; i < (totalHumanPlayers + totalComputerPlayers); i++)

You can hold both types of car in your array, just as you did (declaring the array to be of type MainCar), remember that MainCar can be a ComputerCar or a PlayerCar, you will need to cast to make use one of them (if you need to access to specific members of PlayerCar or ComputerCar) like this:

PlayerCar player = (PlayerCar)carsArray[x];

But in your case, if you only need coords at MainCar you just can access them directly (if they are members of MainCar of course) like:

carsArray[i].location.x

or

carsArrays[i].x

Just remember to initialize correctly the array. (Don't overlap your data)

EDIT:

And to determine if a car is of one type or another use the instanceof operator, here's an example:

if (carVar instanceof PlayerCar) { PlayerCar player = (PlayerCar)carVar; }

like image 120
lepi Avatar answered Apr 24 '26 05:04

lepi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!