Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

Classes in arrays

  Asked By: Hondo    Date: Sep 23    Category: Java    Views: 610
  

I'm having a bit of a mental block and am not sure the following can even be
done.

I have a virtual base class, say Animal. Most of the methods are virtual except
for the method death() { decay };

I use this as a base class for a new class, cheetah.

I also use it as a base class for gazelle.

Both have exactly the same methods but the implimentation of them are different.

Now, I want to make a 200 element array which holds the animals found on a
section of grassland.

How do I do this? How do I access the methods for the animals? I don't know if
grasslandAnimals[120] is a cheetah or a gazelle so I can't typecast it. I'm a
bit confused.

Share: 

 

1 Answer Found

 
Answer #1    Answered By: Angel Watkins     Answered On: Sep 23

Animal[] animals = new Animal[200];
animals[0] = new Animal();
animals[1] = new Cheetah();
animals[2] = new Gazelle();
animals[3] = new Animal();
animals[4] = new Cheetah();
animals[5] = new Gazelle();
animals[6] = new Animal();
animals[7] = new Cheetah();
animals[8] = new Gazelle();

for (int i = 0; i < animals.length;i++)
if (animals[i] == null) {
System.out.println("Not initialized.");
} else{
if (animals instanceof Cheetah) System.out.println("animals[" + i
+ "] is a Cheetah");
if (animals instanceof Gazelle) System.out.println("animals[" + i
+ "] is a Gazelle");
if (animals instanceof Cheetah) System.out.println("animals[" + i
+ "] is an Animal");
}
}

 
Didn't find what you were looking for? Find more on Classes in arrays Or get search suggestion and latest updates.




Tagged: