I just found this pretty intriguing. Usually when we make an array we specify the type of the array ie. char [] arrayA = new char [] { 3 }
. But, when dealing with objects, does Java treat each as a specific type, or does it treat these arrays from the specific classes? In other words, can we make an array of different objects from different classes in the same array?
Asked
Active
Viewed 178 times
-2

Adrian Mole
- 49,934
- 160
- 51
- 83

William Wang
- 1
- 2
-
1Why dont you try it? – NotZack Sep 27 '20 at 18:35
-
I would try but I'm not sure how exactly to do so. – William Wang Sep 27 '20 at 18:36
-
4Does this answer your question? [Java Array with multiple data types](https://stackoverflow.com/questions/23957581/java-array-with-multiple-data-types) – flaxel Sep 27 '20 at 18:36
-
Thank you, I'll see if it works. – William Wang Sep 27 '20 at 18:37
1 Answers
1
If you make an array like char [], it can only hold objects typed char.
If you would like to hold multiple different Object types with no related Interface you can use Object [] to hold a list of Objects. Cast the object by using (Object). Cast the object back to its original type when done.
If your classes implement the same interface you can use a list of the interface type to hold the objects for more clarity.
Interface Listable
foo implements Listable
bar implements Listable
Listable [] can hold both foo and bar.

Joshua Peddle
- 31
- 1