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?
-
1Why dont you try it?NotZack– NotZack2020-09-27 18:35:26 +00:00Commented Sep 27, 2020 at 18:35
-
I would try but I'm not sure how exactly to do so.William Wang– William Wang2020-09-27 18:36:15 +00:00Commented Sep 27, 2020 at 18:36
-
4Does this answer your question? Java Array with multiple data typesflaxel– flaxel2020-09-27 18:36:44 +00:00Commented Sep 27, 2020 at 18:36
-
Thank you, I'll see if it works.William Wang– William Wang2020-09-27 18:37:34 +00:00Commented Sep 27, 2020 at 18:37
Add a comment
|
1 Answer
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.