-2

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?

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

1 Answers1

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.