user1464139
user1464139

Reputation:

Can I create a object array to hold different objects in Java?

Is it possible to do something like this in Java?

Object[] objArray = { new Car(), new Human() }

I read that the array elements all have to be the same type but aren't these all of type Object ?

Upvotes: 0

Views: 2532

Answers (5)

adranale
adranale

Reputation: 2874

Yes, it is possible! Since Object is the upper class of all classes

Upvotes: 0

Aaron Digulla
Aaron Digulla

Reputation: 328604

Yes, it's possible but not useful often and always dangerous.

If you want to put some objects into a collection (list or array), the type of the collection must allow for a common ancestor. Since Object is the common ancestor to all OO types in Java, you can put anything into it (and, with Java 6's autoboxing, even primitives).

The problems start when you work with the elements in the list. As long as you only need to call methods which the common ancestor type provides, everything is fine.

But eventually, you will want to call methods of the Car type and that means you'll have to identify the instances in the collection (which is somewhat slow and pretty clumsy in the code) and use casts (always a good sign for bad code).

Upvotes: 3

JB Nizet
JB Nizet

Reputation: 691745

Inheritance is used to define a is-a relationship. Since every class in Java extends java.lang.Object (either directly or indirectly), a Car instance is-a Object instance, and a Human instance is-a Object instance.

So, of course, an array of objects can hold humans, cars, and every other kind of object.

Upvotes: 1

SimonSez
SimonSez

Reputation: 7769

Yes, it's possible to do something like that but its not very OO-like.

Make sure you do an explicit cast when accessing your objects, e.g.

Human h = (Human) objArray[1337];

Have Fun!

Upvotes: 0

rtheunissen
rtheunissen

Reputation: 7435

You're correct, that works perfectly okay even though it's not considered to be good OO practice.

Upvotes: 2

Related Questions