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 ?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
Objectis 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
Cartype 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).