Wayne Geissinger
Wayne Geissinger

Reputation: 3

Can you put multiple types of objects in an array?

I have been assigned the task of re-creating the Oregon Trail through java. I have a few requirements - I must have a superclass - Location - and sublcasses - Trail, Landmark, City, Fort, and River and I must use and instantiate them all. I am currently thinking that the best way to approach re-creating the game would be to have a for loop (each loop representing one day) and decrement miles to next landmark, execute random chances to be sick, decrement food rations, etc. If I do it this way, the only logical way that I see to differentiate from location to location would be to create an instance of each class for each stop in the game (so Independence would be a city, Kansas River would be a River) but my question is, is there a way for me to put all of these instances into one object array even though they are different classes (from the same superclass)? I haven't been able to find any info on the syntax to do this.

Upvotes: 0

Views: 1050

Answers (2)

Nechemia Hoffmann
Nechemia Hoffmann

Reputation: 2507

Yes you can. What you are tying to do is called abstraction, and might be the most powerful feature of polymorphism. The is-a relationship created by extending the allows to allow us to program for the future, without knowing what the future will bring.

In your case you can create a new Location[] this will instantiate a new array of type Location, which will store references to Location objects. By definition, since a Trail is-a Location, you will be able to store references to Trail objects in a Location array. The same applies to all other subclasses of Location.

This explains Hari Lamichhane:

Location[] all = new Location[] {    
new Trail(),
new LandMark(),
new City()
};

However, the reference to that new Trail() object is actually stored as a Location reference (that's why you can store that reference in that new Location[]. Since Java is type safe, without safety casting that reference to a Trail reference you will not be able to access any methods not implemented in the super class (Location).

Lastly, if the implementation of each type of location is radically different one from the next you may want to consider a interface or abstract class.

Upvotes: 0

Hari Lamichhane
Hari Lamichhane

Reputation: 530

Of course you can do that in Java.

As all of your classes are inheriting from Location class. You can simply create array like this.

Location[] all = new Location[] {
  new Trail(),
  new LandMark(),
  new City()
};

Upvotes: 2

Related Questions